我如何告诉group_by
按所有列(给定列除外)对数据进行分组?
如果是aggregate
,那就是aggregate(x ~ ., ...)
.
我试了group_by(data, -x)
次,但结果是按x的负方向分组(即与按x分组相同).
我如何告诉group_by
按所有列(给定列除外)对数据进行分组?
如果是aggregate
,那就是aggregate(x ~ ., ...)
.
我试了group_by(data, -x)
次,但结果是按x的负方向分组(即与按x分组相同).
您可以使用标准判断(group_by_
而不是group_by
)来实现这一点:
# Fake data
set.seed(492)
dat = data.frame(value=rnorm(1000), g1=sample(LETTERS,1000,replace=TRUE),
g2=sample(letters,1000,replace=TRUE), g3=sample(1:10, replace=TRUE),
other=sample(c("red","green","black"),1000,replace=TRUE))
dat %>% group_by_(.dots=names(dat)[-grep("value", names(dat))]) %>%
summarise(meanValue=mean(value))
g1 g2 g3 other meanValue <fctr> <fctr> <int> <fctr> <dbl> 1 A a 2 green 0.89281475 2 A b 2 red -0.03558775 3 A b 5 black -1.79184218 4 A c 10 black 0.17518610 5 A e 5 black 0.25830392 ...
关于dplyr
中标准与非标准判断的更多信息,请参见this vignette.
dplyr
0.7.0为了回应@ÖmerAn的 comments :在dplyr
0.7.0中,group_by_at
是最好的 Select (如果我错了,请有人纠正我).例如:
dat %>%
group_by_at(setdiff(names(dat), "value")) %>%
summarise(meanValue=mean(value))
# Groups: g1, g2, g3 [?] g1 g2 g3 other meanValue <fctr> <fctr> <int> <fctr> <dbl> 1 A a 2 green 0.89281475 2 A b 2 red -0.03558775 3 A b 5 black -1.79184218 4 A c 10 black 0.17518610 5 A e 5 black 0.25830392 6 A e 5 red -0.81879788 7 A e 7 green 0.30836054 8 A f 2 green 0.05537047 9 A g 1 black 1.00156405 10 A g 10 black 1.26884303 # ... with 949 more rows
让我们确认两种方法给出相同的输出(在dplyr
0.7.0中):
new = dat %>%
group_by_at(setdiff(names(dat), "value")) %>%
summarise(meanValue=mean(value))
old = dat %>%
group_by_(.dots=names(dat)[-grep("value", names(dat))]) %>%
summarise(meanValue=mean(value))
identical(old, new)
# [1] TRUE