dplyr 包在流式数据处理方面的流畅性让我感到非常震惊。最近我急于解决一个问题,为每个组ID生成一个新的数据帧,并将这些小数据帧组合成最终的更大的数据帧。一个玩具示例:
input.data.frame %>%
group_by(gid) %>%
{some operation to generate a new data frame for each group} ## FAILED!!!!
在 dplyr 中,函数mutate
向每个组添加新列并summarise
为每个组生成摘要,都不能满足我的要求。(我错过了什么?)
或者,使用ddply
plyr 包,之前的 dplyr 交互,我可以通过
ddply(input.data.frame, .(gid), function(x) {
some operation to generate a new data frame for each group
}
但不足之处是,当我加载 plyr 包时,dplyr 中的一些功能将无法使用。
以下是 G. Grothendieck 对类似问题的回答之后的示例。在“dplyr”输出中添加行 https://stackoverflow.com/questions/23621332/adding-rows-in-dplyr-output
首先我们生成一个包含 x 和 g 的数据框。 x中有9个随机数,g中有3组a、b、c。我们想从每组中选择 2 个最大的数字。重要的是要记住 do 需要一个数据帧作为返回值。
library(dplyr)
set.seed(1)
dat <- data.frame(x=runif(9),g=rep(letters[1:3],each=3))
dat
x g
1 0.1765568 a
2 0.6870228 a
3 0.3841037 a
4 0.7698414 b
5 0.4976992 b
6 0.7176185 b
7 0.9919061 c
8 0.3800352 c
9 0.7774452 c
## this works
dat %>% dplyr::group_by( g ) %>% do( data.frame(x=tail(sort(.$x),2)) )
## this works too
dat %>% dplyr::group_by( g ) %>% do( .[tail(order(.$x),2),] )
x g
(dbl) (fctr)
1 0.3841037 a
2 0.6870228 a
3 0.7176185 b
4 0.7698414 b
5 0.7774452 c
6 0.9919061 c
## no error, but x is treated as a 1x1 data frame
dat %>% dplyr::group_by( g ) %>% do( x=tail(sort(.$x),2) )
g x
(fctr) (chr)
1 a <dbl[2]>
2 b <dbl[2]>
3 c <dbl[2]>
## you need a function to do more complicated stuff
top2x <- function(df) { df[tail(order(df$x),2),] }
dat %>% dplyr::group_by( g ) %>% do( top2x(.) )
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)