-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathLec03_Notes_part2.R
393 lines (302 loc) · 8.9 KB
/
Lec03_Notes_part2.R
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
# Lecture 3 notes, part 2
# Working Data Frames
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
## Loading and Saving Data
#just some setup
#loading .dta
library(foreign)
org_example <- read.dta(
file = "https://github.com/EconomiCurtis/econ294_2015/raw/master/data/org_example.dta")
#Save as .RData
save(
org_example,
file = "data/org_example.RData"
)
# load RData
load(
file = "data/org_example.RData"
)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Describe your data
str(org_example)
# note all the different data types for the 33 variables
# list variable names
names(org_example)
summary(org_example) #helpful for numeric varaibles
# summarize one variable
# The "$" operator from lists
table(org_example$year) #table is a handy function, freq count
unique(org_example$year)
class(org_example$educ)
levels(org_example$educ)
table(org_example$educ)
sum(
is.na(org_example$educ)
) #however, it doesn't count NAs
# View(org_example) #open a snippet in RStudio
# lots of options for filter, sort.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Adding, removing, editing columns
# cbind function
df <- cbind(
col1 = rnorm(100),
col2 = runif(100)
)
#beware recycling, length of new column should match length of old
# add column with assignment
# create new "colGrad" variable
# do they have College or Advanced?
table(org_example$educ)
"colGrad" %in% names(org_example)
org_example$colGrad <- ifelse(
test = (org_example$educ %in% c("College","Advanced")),
yes = 1,
no = 0
)
table(org_example$educ)
table(org_example$colGrad) #tab completion
# 82307+164576 = 246883, looks good
# summarize by...
# summarize rw, by year
#with tapply
# a little messy
#vector of mean rw, by year
temp.4.mean <- tapply(
X = org_example$rw,
INDEX = org_example$year,
summary
)
temp.4.mean
typeof(temp.4.mean)
class(temp.4.mean)
# applying functions to data.frames
# lm example
glm_probit <- glm(
unem ~ educ,
family = (binomial(link = "probit")),
data = subset(org_example,
nilf == 0 & year == 2008)
)
summary(glm_probit)
############ end of lec 3
org_example <- read.dta(
file = "https://github.com/EconomiCurtis/econ294_2015/raw/master/data/org_example.dta")
d <- subset(org_example, year == 2008)
d <- subset(d, nilf == 0)
glm_probit<-glm(unem~educ,d,family=binomial(link="probit"))
summary(glm_probit)
# And a column as function of another
org_example$rw_log <- log(org_example$rw)
# vectorized operation (a for loop over a vector)
# standardize and normalize
mean(org_example$rw, na.rm = T)
sd(org_example$rw, na.rm = T)
org_example$rw_std <- I(
(org_example$rw - mean(org_example$rw, na.rm = T)) / sd(org_example$rw, na.rm = T)
)
system.time({
# but what about, standardize by year? year and education level?
stndz <- function(x){
(x - mean(x, na.rm = T)) / sd(x, na.rm = T)
}
temp <- split(
org_example$rw, c(org_example$year)
)
temp.2 <- lapply(
temp,
stndz
)
temp.3 <- unsplit(
temp.2,
c(org_example$year)
)
org_example$rw_std.year <- temp.3
mean(subset(org_example, year == 2013)$rw, na.rm = T) # [1] 21.84623
sd(subset(org_example, year == 2013)$rw, na.rm = T) # [1] 16.74968
# (57.48-21.84) / 16.74 # [1] 2.129032 # yep!!
})
# Using Aggregate
aggregate(
)
# Wow! Getting complicated!!, imagine this for year + educ!
# but don't fret
# introduce dplyr tools
require(dplyr)
system.time({
org_example <- org_example %>% # magrittr
dplyr::group_by(year) %>% # dplyr::group_by(year, educ) %>%
dplyr::mutate(
rw_std.year2 = stndz(rw)
)
}) # almost 5 times faster
sum(org_example$rw_std.year == org_example$rw_std.year2, na.rm = T) / sum(!is.na(org_example$rw_std.year))
#all are exactly the same!
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# dplyr + tidyr
# your friend
install.packages("dplyr")
library(dplyr)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Select certain columns (dplyr::select)
# select certain variables
dim(org_example)
names(org_example)
# see str(org_example)
org_example.nu <- dplyr::select(
org_example,
year, month, educ, rw #list columns you want to keep
)
dim(org_example.nu)
names(org_example.nu)
# tons of great tools
?select #see special functions
org_example.nu <- dplyr::select(
org_example,
year, month, matches("edu"), ends_with("w")
)
names(org_example.nu)
#easy way to change names of variales
org_example.nu <- dplyr::select(
org_example,
YEAR = year, MO = month, matches("edu"), ends_with("w")
)
names(org_example.nu)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Subsetting (dplyr::filter)
# filter (subset) rows/obs by matching conditions
# overloaded function name
?filter
?dplyr::filter
system.time({
org_example.nu <- subset(
org_example,
year == 2008 | rw > 10
)
})
system.time({
org_example.nu <- dplyr::filter(
org_example,
year == 2008 | rw > 10
)
}) #often much faster
# Multiple logic rules:
# < Less than != Not equal to
# > Greater than %in% Group membership
# == Equal to is.na is NA
# <= Less than or equal to !is.na is not NA
# >= Greater than or equal to &,|,! Boolean operators
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Sorting (dplyr::arrange)
?arrange
org_example.nu <- dplyr::arrange(
org_example,
year, month
)
View(org_example.nu)
# from earliest year, to more recent, down
# within year, sort month from earliest to biggest
org_example.nu <- dplyr::arrange(
org_example,
-year, -month
)
View(org_example.nu) #opposite of that sorting
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Adding or Changing Columns (dplyr::mutate)
# Creates new variables
stndz <- function(x){
(x - mean(x, na.rm = T)) / sd(x, na.rm = T)
}
org_example.nu <- dplyr::mutate(
org_example,
rw.std = stndz(rw)
)
View(org_example.nu)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Summarize (dplyr::summarize)
# summary stats on variables
org_example.nu <- dplyr::filter(
org_example,
year == 2008, state == "CA", educ == "College")
org_example.nu <- dplyr::summarise(
org_example.nu,
rw_mean = mean(rw, na.rm = T),
rw_sd = sd(rw, na.rm = T),
obs = length(rw)
)
org_example.nu
# 2499 College CA obs in 2008
# mean wage 31.95
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Piping magrettr %>% operator
# the real power of dplyr (and tidyr ggplot to come) is combining multiple functions
# Example:
# - just the year, month, rw, educ and age column
# - rename these columns
# - filter by a few conditions
# - add a new variable
# - sort it
# Do this:
# - multiple assignments...?
org_example.nu <- dplyr::select(
org_example, YEAR = year, MO = month, RealWage = rw, Educ = educ, Age = age)
org_example.nu <- dplyr::filter(
org_example.nu, YEAR > 1900 & !is.na(RealWage))
org_example.nu <- dplyr::mutate(
org_example.nu, rw.std = stndz(RealWage))
org_example.nu <- dplyr::arrange(
org_example.nu, YEAR, MO)
str(org_example.nu)
# - many functions ... odd orders
org_example.nu <- dplyr::arrange(
dplyr::mutate(
dplyr::filter(
dplyr::select(
org_example,
YEAR = year, MO = month, RealWage = rw, Educ = educ, Age = age
),
YEAR > 1900 & !is.na(RealWage)
),
rw.std = stndz(RealWage)
),
YEAR, MO
)
str(org_example.nu)
org_example.nu <- org_example %>%
dplyr::select(
YEAR = year, MO = month, RealWage = rw, Educ = educ, Age = age
) %>%
dplyr::filter(
YEAR > 1900 & !is.na(RealWage)
) %>%
dplyr::mutate(
rw.std = stndz(RealWage)
) %>%
dplyr::arrange(
YEAR, MO
)
str(org_example.nu)
# walk through each step
# note the %>% operator must be on the same line!
# this is much much better!
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Grouping (dplyr::group_by)
# sort, add, summarize, by a grouping variable or variables.
# Let's find average real wages by year, month, state, educ
org_example$state <- factor(
org_example$state,
levels(org_example$state)[order(levels(org_example$state))]
) #the state was out of order, it was annoying me
Wage.sum <- org_example %>%
dplyr::group_by(year, month, state, educ) %>%
dplyr::summarise(
rw.mean = mean(rw, na.rm = T),
rw.median = median(rw, na.rm = T),
count = length(rw)
)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Merging (dplyr::join)
# full_join, left_join, right_join
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Reshaping your data
# tidyr