Jak użyć dplyr, aby zastosować funkcję do wszystkich kolumn spoza grupy by?

Próbuję użyć pakietu dplyr, aby zastosować funkcję do wszystkich kolumn danych.ramki, które nie są zgrupowane, co zrobiłbym z aggregate():

aggregate(. ~ Species, data = iris, mean)

Gdzie {[3] } stosuje się do wszystkich kolumn nie używanych do grupowania. (Tak, Wiem, że mogę użyć agregatu, ale staram się zrozumieć dplyr.)

Mogę użyć summarize w ten sposób:

species <- group_by(iris, Species)
summarize(species,
          Sepal.Length = mean(Sepal.Length),
          Sepal.Width = mean(Sepal.Width))

Ale czy istnieje sposób, aby mean() zastosować do wszystkich kolumn, które nie są zgrupowane, podobnie jak zapis . ~ aggregate()? Mam data.ramka z 30 kolumnami, które chcę agregować, więc wypisywanie poszczególnych stwierdzeń nie jest idealne.

 17
Author: kmm, 2014-03-25

2 answers

Jeśli chcesz wypróbować eksperymentalny dplyr, możesz wypróbować nowe (i wciąż eksperymentalne) summarise_each():

devtools::install_github("hadley/dplyr", ref = "colwise")

library(dplyr)
iris %.%
  group_by(Species) %.%
  summarise_each(funs(mean))
## Source: local data frame [3 x 5]
## 
##      Species Sepal.Length Sepal.Width Petal.Length Petal.Width
## 1     setosa        5.006       3.428        1.462       0.246
## 2 versicolor        5.936       2.770        4.260       1.326
## 3  virginica        6.588       2.974        5.552       2.026

iris %.%
  group_by(Species) %.%
  summarise_each(funs(min, max))
## Source: local data frame [3 x 9]
## 
##      Species Sepal.Length_min Sepal.Width_min Petal.Length_min
## 1     setosa              4.3             2.3              1.0
## 2 versicolor              4.9             2.0              3.0
## 3  virginica              4.9             2.2              4.5
## Variables not shown: Petal.Width_min (dbl), Sepal.Length_max (dbl),
##   Sepal.Width_max (dbl), Petal.Length_max (dbl), Petal.Width_max (dbl)

Opinie bardzo mile widziane!

Pojawi się to w dplyr 0.2.

 34
Author: hadley,
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-03-25 22:01:33

To doprowadzi Cię prawie do końca dplyr.

h = iris %.%
  group_by(Species) %.%
  do(function(d){
    sapply(Filter(is.numeric, d), mean)  
  })

as.data.frame(h)
 4
Author: Ramnath,
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-03-25 20:07:40