r - How do I access all the elements of a data.frame using group_by (dplyr)? -
suppose have data.frame 'df':
speed dist lan 4 2 "bra" 4 10 "bra" 7 4 "bra" 7 22 "col" 8 16 "col" 9 10 "col" 10 18 "fin" ...
i want realize operations on speed , dist groupin_by lan, example, try print values. how do that?
i've tried manner cannot achieve success:
df %>% group_by(lan) %>% (function(.) { print(.$speed) print(.$dist) })
you should use do
@r2evans suggested in comments above. better return original data.frame
, can continue work it. in case instance might want calculate mean speed , mean dist after:
df %>% group_by(lan) %>% do({ cat("lan = ", .$lan[1], "\n") print(.$speed) print(.$dist) . }) %>% summarise(mean(speed), mean(dist))
and can show output, here's example mtcars
.
mtcars %>% group_by(cyl) %>% do({cat("cyl = ", .$cyl[1], "\n") print(.$mpg) print(.$wt) .}) %>% summarise(mean(mpg), mean(wt)) ## cyl = 4 ## [1] 22.8 24.4 22.8 32.4 30.4 33.9 21.5 27.3 26.0 30.4 21.4 ## [1] 2.320 3.190 3.150 2.200 1.615 1.835 2.465 1.935 2.140 1.513 2.780 ## cyl = 6 ## [1] 21.0 21.0 21.4 18.1 19.2 17.8 19.7 ## [1] 2.620 2.875 3.215 3.460 3.440 3.440 2.770 ## cyl = 8 ## [1] 18.7 14.3 16.4 17.3 15.2 10.4 10.4 14.7 15.5 15.2 13.3 19.2 15.8 15.0 ## [1] 3.440 3.570 4.070 3.730 3.780 5.250 5.424 5.345 3.520 3.435 3.840 3.845 3.170 3.570 ## source: local data frame [3 x 3] ## ## cyl mean(mpg) mean(wt) ## 1 4 26.66364 2.285727 ## 2 6 19.74286 3.117143 ## 3 8 15.10000 3.999214
Comments
Post a Comment