-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbiling.rmd
389 lines (330 loc) · 9.07 KB
/
biling.rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
---
title: "bilingual R Markdown"
author: "theophano mitsa"
date: "August 1, 2019"
output: html_document
---
```{r setup, include=FALSE}
library(reticulate)
use_python("C:/Users/Theo/Anaconda3/python.exe")
knitr::opts_chunk$set(echo = TRUE)
```
Discover the Python that will be used
```{r}
py_discover_config()
```
1. DATAFRAME CREATION, SUMMARIZATION
a. Read a dataframe from scratch
IN R
```{r}
library(tidyverse)
set.seed(3)
mat1<-matrix(rnorm(6,12,3), nrow=2)
dimnames(mat1)=list(c("dep1","dep2"),c("Tom","Jim","Sam"))
DepositFrame=as.data.frame(mat1)
print(DepositFrame)
```
IN PYTHON
```{python}
import numpy as np
import pandas as pd
ChildAgeFrame = pd.DataFrame(np.array(([15, 0],[69,3], [35, 2])),
columns=['age', 'children'], index=['Tes', 'Linda', 'Kate'])
print(ChildAgeFrame)
ChildAgeFrame.describe()
#Print the Tes column
print(ChildAgeFrame.loc['Tes'])
#Alternate way to create a DataFrame
HotelFrame = pd.DataFrame({'Room Type': ['Regular','Suite', 'Regular','Lux Suite','Suite'],'Floor':['1','2','3','3','2']})
print(HotelFrame)
```
b. Read a dataframe from a csv file
IN R
```{r}
heart_R<-read.csv("heart.csv",header=TRUE, fileEncoding="UTF-8-BOM")
#print dimensions
dim(heart_R)
#print names of columns
names(heart_R)
```
IN PYTHON
```{python}
import pandas as pd
heart_P=pd.read_csv('heart.csv')
#read only certain columns from a csv file
drop_cols=['thal','thalach']
heart_Pr=pd.read_csv('heart.csv',usecols=lambda cc : cc not in drop_cols, index_col=False)
#print dimensions
print(heart_P.shape)
#print names of columns
print(heart_P.columns)
```
c. Data Summarization
In R
```{r}
#print first rows
head(heart_R)
#Print some basic info about the dataframe
glimpse(heart_R)
str(heart_R)
summary(heart_R)
#Alternate way to summarize variables
library(prettyR)
describe(heart_R)
#sort according to cholesterol
heart_R%>% arrange(chol)%>%head()
#Use tapply() to group and compute functions within groups
tapply(heart_R$chol,heart_R$sex,mean)
#compute the mean after grouping with group_by()
heart_R%>%group_by(sex)%>%summarise_all(~mean(.,na.rm=TRUE))
#Compute counts of groups
heart_R%>%count(sex)
heart_R%>%count(cp,sort=TRUE)
heart_R%>%count(cp,fbs, sort=TRUE)
```
In Python
```{python}
import pandas as pd
heart_P=pd.read_csv('heart.csv')
#print first rows
print(heart_P.head(5))
#Print some basic info about the dataframe
heart_P.describe()
#Count grouped cases
heart_P.groupby('fbs').count()
#Count the mean of grouped cases
heart_P.groupby(['sex','fbs']).count()
heart_P.groupby(['sex','fbs']).mean()
```
2. INDEX-BASED SELECTION: SELECT ROWS,COLUMNS, ELEMENTS USING INDICES
IN R
```{r}
#Print first row
print(DepositFrame[1,])
#Print first column
print(DepositFrame[,1])
#Print first element
DepositFrame[1,1]
```
IN PYTHON
```{python}
import numpy as np
import pandas as pd
ChildAgeFrame = pd.DataFrame(np.array(([15, 0], [69, 3],[35, 2])),
columns=['age', 'children'], index=['Tes', 'Linda', 'Kate'])
#Select first row. Returns Series.
print(ChildAgeFrame.iloc[0])
#Select first row. Returns Dataframe.
print(ChildAgeFrame.iloc[[0]])
#Select first column
print(ChildAgeFrame.iloc[:,0])
#Select last column
print(ChildAgeFrame.iloc[:,-1])
#Select first element
print(ChildAgeFrame.iloc[0,0])
#Select first 2 rows
print(ChildAgeFrame.iloc[0:2])
#Select first 2 columns
print(ChildAgeFrame.iloc[:,0:2])
```
3.NON-INDEX-BASED SELECTION
a. Column Selection Using Column Names
IN R
```{r}
#selecting a single column in basic R
DepositFrame["Tom"]
#selecting a multitude of columns using select()
DepositFrame%>%select("Tom","Sam")
```
IN PYTHON
```{python}
import numpy as np
import pandas as pd
ChildAgeFrame = pd.DataFrame(np.array(([15, 0], [69, 3], [35,2])),
columns=['age', 'children'], index=['Tes', 'Linda', 'Kate'])
print(ChildAgeFrame[['age']])
```
b.Column Selection Using Regular Expressions, Logical Conditions
IN R
```{r}
#Filter using regex
DepositFrame%>%select(matches("S.+m"))%>%glimpse()
#Filter based on a logical expression
DepositFrame %>% select(matches("m"))%>%
select_if(~max(.,na.rm=TRUE)<12)%>%glimpse()
```
IN PYTHON
```{python}
import numpy as np
import pandas as pd
ChildAgeFrame = pd.DataFrame(np.array(([15, 0], [69, 3], [39,2])),
columns=['age', 'children'], index=['Tes', 'Linda', 'Kate'])
Child_select=ChildAgeFrame.filter(regex='a.+e',axis=1)
print(Child_select)
```
3.c Non-Index-Based Row Selection: With Logical Expressions EXPRESSIONS And/Or Row Names
IN R
```{r}
#Print the age of men with high cholesterol
#With basic R
MEN_WITH_HIGH_CHOL<-heart_R$chol > 280 & heart_R$sex==1
print(heart_R[MEN_WITH_HIGH_CHOL,1])
#with dplyr
filtered<-filter(heart_R,chol > 280 & sex==1)
print(filtered[1])
#print any rows that contain a value greater than 280
heart_n<-heart_R%>%filter_all(any_vars(.>280))
print(heart_n)
```
IN PYTHON
```{python}
import numpy as np
import pandas as pd
#Select row using logical condition
heart_P=pd.read_csv('heart.csv')
df=heart_P[(heart_P['chol']> 200) & (heart_P['thalach']==178)]
print(df)
#Select row using row name
dfnew = pd.DataFrame(np.array(([15,0], [69,3],[35,2])),
columns=['age', 'children'], index=['Tes', 'Linda', 'Kate'])
print(dfnew.loc['Linda'])
```
4. DELETE COLUMNS/ROWS
IN R
```{r}
#Delete using column name
print(DepositFrame)
Depnew<-DepositFrame%>%select(-c("Sam"))
Depnew
#Delete using starts_with.
Depnew<-DepositFrame%>%select(-starts_with("J"))
Depnew
#Delete row
set.seed(3)
mat1<-matrix(rnorm(6,12,3), nrow=2)
dimnames(mat1)=list(c("dep1","dep2"),c("Tom","Jim","Sam"))
mat1
df=as.data.frame(mat1)
names<-rownames(df)
names
todrop=names[1]
todrop
df2<-df[!(rownames(df)%in%todrop),]
print(df2)
```
IN PYTHON
```{python}
import pandas as pd
HotelFrame = pd.DataFrame({'Room Type': ['Regular','Suite', 'Regular','Lux Suite','Suite'],'Floor':['1','2','3','3','2']})
#Delete a column using its name
Hotelnew=HotelFrame.drop('Floor', axis=1)
print(Hotelnew)
#Alternate way
Hotelnew=HotelFrame.drop(columns=['Floor'],axis=1)
print(Hotelnew)
#Delete Row
Hotelnew=HotelFrame.drop([0])
print(Hotelnew)
```
5. ADD ROW/ COLUMN
IN R
```{r}
#ADD COLUMN
DepositFrame$Brandon<-c(9,12)
#Using mutate, transmute. Transmute only keeps the new vars
dfnew<-mutate(DepositFrame,sumdep=Tom+Jim, Sam=NULL)
print(dfnew)
#ADD ROW
addit_row<-data.frame('Tom'=11.0, 'Jim'=12.2,'Sam'=10.2,'Brandon'=11.3)
df2<-rbind(DepositFrame,addit_row)
df2
#Combine group by and mutate to do calculations within groups.
heart_Rn<-heart_R%>% group_by(sex)%>%mutate(chol_n=chol/mean(chol,na.rm=TRUE))
print(heart_Rn)
```
IN PYTHON
```{python}
import numpy as np
import pandas as pd
HotelFrame = pd.DataFrame({'Room Type': ['Regular','Suite', 'Regular','Lux Suite','Suite'],'Floor':['1','2','3','3','2']})
pets=['No','Yes','No','No','Yes']
HotelFrame['pet']=pets
#Using a map to implement logic
pets_allowed={'Regular':'No','Suite':'Yes','Lux Suite':'No'}
#Add column using the above map
HotelFrame['PETS']=HotelFrame['Room Type'].map(pets_allowed)
#ADD a ROW
dfadd=HotelFrame.append({'Room Type':'Regular','Floor':'1',
'pet':'No','PETS':'No'}, ignore_index=True)
print(dfadd)
```
6. APPLY A FUNCTION TO ROWS/COLUMNS OF A DATAFRAME
IN R
```{r}
#Compute mean over columns
apply(DepositFrame,2,mean)
#Compute mean over rows
apply(DepositFrame,1,mean)
```
IN PYTHON
```{python}
import numpy as np
import pandas as pd
ChildAgeFrame = pd.DataFrame(np.array(([15, 0], [69,3],[35,2])),
columns=['age', 'children'], index=['Tes', 'Linda', 'Kate'])
#Compute the mean of the columns
print(ChildAgeFrame.apply(np.mean,axis=0))
#Apply a lambda function to all elements
print(ChildAgeFrame.apply(lambda x: x*5))
```
7. SAMPLING A DATAFRAME
IN R
```{r}
set.seed(5)
#Sample 3 rows without replacement
heart_R %>% sample_n(3, replace = FALSE)
# Sample 1% of rows, without replacement
heart_R %>% sample_frac(0.01, replace = FALSE)
```
IN PYTHON
```{python}
import numpy as np
import pandas as pd
heart_P=pd.read_csv('heart.csv')
s1=heart_P.sample(n=3)
s2=heart_P.sample(frac=0.01)
```
8. COMPARE DATA LOADING BETWEEN DATA.TABLE AND DATAFRAME
```{r}
library(data.table)
system.time(student1<-read.csv("student_data.csv",header=TRUE, fileEncoding="UTF-8-BOM"))
system.time(student2<-fread("student_data.csv"))
```
9. COMPARE FILTERING IN DPLYR AND DATA.TABLE
```{r}
library(data.table)
heart_RDT=fread("heart.csv",header=TRUE)
ff<-heart_R%>%filter(chol > 280 & sex==1)
#Mean age of men with chol > 280
mean(ff[,1])
#Mean age computed from a data.table
dd<-heart_RDT[chol > 280 & sex==1,.(mm=mean(age))]
dd
```
10. IMPLEMENT/COMPARE PARALLELIZATION/ FUNCTION COMPILATION
```{r}
library(parallel)
library(compiler)
k<-detectCores()
c1<-makeCluster(4)
mysquare<-function(num){return(num^2)}
#Compile the function
gb<-cmpfun(mysquare)
set.seed(2)
sample_numbers <- sample(10000000, 10000000)
system.time(sapply(sample_numbers,mysquare))
system.time(sapply(sample_numbers,gb))
system.time(parSapply(c1,sample_numbers, mysquare))
system.time(parSapply(c1,sample_numbers, gb))
stopCluster(c1)
```