dplyr可以汇总几个变量而不列出每个变量吗?

Dav*_*d F 73 r dplyr

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)
Run Code Online (Sandbox Code Playgroud)

使用这个小型数据帧,它很容易编写

summarise(dg,mean(age),mean(bmi),mean(chol))
Run Code Online (Sandbox Code Playgroud)

而且我知道,为了得到我想要的东西,我可以融化,获得手段,然后如dcast

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

但是如果我有> 20个变量和非常多的行呢?在data.table中是否有类似于.SD的东西可以让我采用分组数据框中所有变量的方法?或者,是否有可能以某种方式在分组数据框架上使用lapply?

谢谢你的帮助

rrs*_*rrs 115

dplyr现在有summarise_each:

df %>% 
  group_by(sex) %>% 
  summarise_each(funs(mean))
Run Code Online (Sandbox Code Playgroud)

  • 是的,由于`summarise_each`已被弃用,您现在可能希望使用`summarise_all`或类似的OP应用程序. (3认同)

mne*_*nel 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
Run Code Online (Sandbox Code Playgroud)

我不确定同一个词的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
Run Code Online (Sandbox Code Playgroud)

请注意,有一个github上的问题#178到efficienctly实现plyr成语colwisedplyr.

  • 我说这是目前用dplyr做的最好的.我唯一的改变是用`lapply()`替换`sapply()`,因为没有简化发生. (3认同)