使用dplyr的summarise_each每个函数返回一行? [英] use dplyr's summarise_each to return one row per function?
问题描述
我正在使用dplyr的summarise_each将函数应用于多列数据。一件好事是您可以一次应用多个功能。令人讨厌的是,输出是只有一行的数据框。似乎它应该返回与函数一样多的行,并且要与汇总的列一样多的列。
I'm using dplyr's summarise_each to apply a function to multiple columns of data. One thing that's nice is that you can apply multiple functions at once. Thing is, it's annoying that the output is a dataframe with a single row. It seems like it should return as many rows as functions, with as many columns as columns that were summarised.
library(dplyr)
default <-
iris %>%
summarise_each(funs(min, max), matches("Petal"))
此返回
> default
Petal.Length_min Petal.Width_min Petal.Length_max Petal.Width_max
1 1 0.1 6.9 2.5
我更喜欢
library(reshape2)
desired <-
iris %>%
select(matches("Petal")) %>%
melt() %>%
group_by(variable) %>%
summarize(min=min(value),max=max(value)) %>%
t()
返回接近的内容(不是数据框,但大家都明白了)
which returns something close (not a dataframe, but you all get the idea)
> desired
[,1] [,2]
variable "Petal.Length" "Petal.Width"
min "1.0" "0.1"
max "6.9" "2.5"
summarise_each中是否有执行此操作的选项?
is there an option in summarise_each to do this? If not, Hadley, would you mind adding it?
推荐答案
您可以添加来获得类似的输出dplyr
和 tidyr
软件包。
遵循这些原则可以帮助
You can achieve a similar output combining the dplyr
and tidyr
packages.
Something along these lines can help
library(dplyr)
library(tidyr)
iris %>%
select(matches("Petal")) %>%
summarise_each(funs(min, max)) %>%
gather(variable, value) %>%
separate(variable, c("var", "stat"), sep = "\\_") %>%
spread(var, value)
## stat Petal.Length Petal.Width
## 1 max 6.9 2.5
## 2 min 1.0 0.1
这篇关于使用dplyr的summarise_each每个函数返回一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!