Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
dplyr是否可以在不列出每个变量的情况下总结多个变量?_R_Dplyr - Fatal编程技术网

dplyr是否可以在不列出每个变量的情况下总结多个变量?

dplyr是否可以在不列出每个变量的情况下总结多个变量?,r,dplyr,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 =

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))
我知道为了得到我想要的,我可以融化,得到方法,然后像

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的内容允许我采用分组数据框中所有变量的平均值?或者,是否可以在分组数据帧上以某种方式使用lappy


感谢您的帮助数据表
习惯用法是
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
中的
plyr
习惯用法
colwise
dplyr
中的
plyr
现在有了
总结

df %>% 
  group_by(sex) %>% 
  summarise_each(funs(mean))

我认为
data.table
解决方案将是这里最快、最高效的解决方案。但是你可以有一个很好的“
reforme2
only”解决方案:
dcast(melt(df,id=“sex”),sex~变量,fun.aggregate=mean)
我想这是目前你用dplyr能做的最好的了。我唯一要做的更改是将
sapply()
替换为
lappy()
,因为没有进行简化。请注意,dplyr中现在有summary\u each()和mutate\u each():这里可以找到
summary\u each
替代方案的版本更新:是,由于
summary\u each
已被弃用,您现在可能希望在OP的应用程序中使用
summary\u all
或类似的东西。
df %>% 
  group_by(sex) %>% 
  summarise_each(funs(mean))