Czy dplyr może podsumować kilka zmiennych bez wymieniania każdej z nich? [duplikat]

To pytanie ma już odpowiedź tutaj:

Dplyr jest niesamowicie szybki, ale zastanawiam się, czy czegoś mi brakuje: czy jest możliwe podsumowanie kilku zmiennych. Na przykład:

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)

Z tym małym dataframe, łatwo jest napisać

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

Oraz Wiem, że aby dostać to, czego chcę, mogę stopić, uzyskać środki, a następnie dcast taki jak

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

Ale co jeśli mam > 20 zmiennych i bardzo dużą liczbę wierszy. Czy jest coś podobnego do. SD w danych.tabela, która pozwoli mi wziąć środki wszystkich zmiennych w zgrupowanej ramce danych? Czy jest możliwe użycie lapply na zgrupowanej ramce danych?

Thanks for any help

 69
Author: Ashrith, 2014-01-23

2 answers

Idiom data.table to lapply(.SD, mean), czyli

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

Nie jestem pewien dplyr idiomu na to samo, ale możesz zrobić coś takiego

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

Zauważ, że jest problem z github#178 aby skutecznie zaimplementować idiom plyr colwise w dplyr.

 42
Author: mnel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-23 05:36:35

dplyr teraz ma summarise_each:

df %>% 
  group_by(sex) %>% 
  summarise_each(funs(mean))
 113
Author: rrs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-27 15:25:14