Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

r - use dplyr's summarise_each to return one row per function?

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"))

this returns

> default
  Petal.Length_min Petal.Width_min Petal.Length_max Petal.Width_max
1                1             0.1              6.9             2.5

I'd prefer something like

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" 

is there an option in summarise_each to do this? If not, Hadley, would you mind adding it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...