【问题标题】:Can dplyr summarise over several variables without listing each one? [duplicate]dplyr 可以总结几个变量而不列出每个变量吗? [复制]
【发布时间】:2014-02-13 06:41:21
【问题描述】:

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?

感谢您的帮助

【问题讨论】:

  • 我认为data.table 解决方案在这里将是最快和更有效的。但是你可以有一个很好的“reshape2 only”解决方案:dcast(melt(df, id = "sex"), sex ~ variable, fun.aggregate = mean)

标签: r dplyr


【解决方案1】:

正如一些人所提到的,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))

【讨论】:

  • summarise_each 替代品的版本更新可以在这里找到:stackoverflow.com/a/39284283/5088194
  • 是的,因为 summarise_each 已被弃用,您现在可能想为 OP 的应用程序使用 summarise_all 或类似的东西。
  • summarise_each 已被弃用。 df %>% group_by(sex) %>% summarise(across(everything(), mean))
【解决方案2】:

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 问题 #178 可以有效地在 dplyr 中实现 plyr 成语 colwise

【讨论】:

猜你喜欢
  • 2017-09-08
  • 1970-01-01
  • 2019-12-20
  • 1970-01-01
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-02
相关资源
最近更新 更多