77

dplyr 速度惊人,但我想知道我是否遗漏了什么:是否可以总结几个变量。例如:

library(dplyr)
library(reshape2)

(df=dput(structure(list(sex = structure(c(1L, 1L, 2L, 2L), .Label = c("boy", 
"girl"), class = "factor"), age = c(52L, 58L, 40L, 62L), bmi = c(25L, 
23L, 30L, 26L), chol = c(187L, 220L, 190L, 204L)), .Names = c("sex", 
"age", "bmi", "chol"), row.names = c(NA, -4L), class = "data.frame")))

   sex age bmi chol
1  boy  52  25  187
2  boy  58  23  220
3 girl  40  30  190
4 girl  62  26  204

dg=group_by(df,sex)

有了这个小数据框,写起来很容易

summarise(dg,mean(age),mean(bmi),mean(chol))

而且我知道要得到我想要的,我可以融化,得到手段,然后 dcast 例如

dm=melt(df, id.var='sex')
dmg=group_by(dm, sex, variable); 
x=summarise(dmg, means=mean(value))
dcast(x, sex~variable)

但是,如果我有 >20 个变量和大量行怎么办。data.table 中是否有任何类似于 .SD 的内容,可以让我获取分组数据框中所有变量的平均值?或者,是否可以在分组数据帧上以某种方式使用 lapply ?

谢谢你的帮助

4

2 回答 2

118

正如几个人所提到的,mutate_each()并且summarise_each()不赞成使用新across()功能。

dplyr从1.0.5 版开始回答:

df %>%
  group_by(sex) %>%
  summarise(across(everything(), mean))

原答案:

dplyr现在有summarise_each

df %>% 
  group_by(sex) %>% 
  summarise_each(funs(mean))
于 2014-06-27T15:25:14.633 回答
44

data.table成语是,lapply(.SD, mean)

DT <- data.table(df)
DT[, lapply(.SD, mean), by = sex]
#     sex age bmi  chol
# 1:  boy  55  24 203.5
# 2: girl  51  28 197.0

我不确定dplyr同一件事的成语,但你可以做类似的事情

dg <- group_by(df, sex)
# the names of the columns you want to summarize
cols <- names(dg)[-1]
# the dots component of your call to summarise
dots <- sapply(cols ,function(x) substitute(mean(x), list(x=as.name(x))))
do.call(summarise, c(list(.data=dg), dots))
# Source: local data frame [2 x 4]

#    sex age bmi  chol
# 1  boy  55  24 203.5
# 2 girl  51  28 197.0

请注意,有一个 github issue # 178可以有效地实现.plyrcolwisedplyr

于 2014-01-22T23:34:26.507 回答