dplyr:汇总每一列和返回列表列

时间:2018-01-27 15:31:45

标签: r dplyr summarize

我希望使用自定义汇总函数汇总每个列,该函数将根据数据返回不同大小的元素。

假设我的汇总函数是这样的:

mysummary <- function(x) {quantile(x)[1:sample(1:5, 1)] %>% as_tibble}

它可以应用于一列:

cars %>% summarise(speed.summary = list(mysummary(speed)))

但我无法找到使用summarise_all(或类似的东西)实现此目的的方法。

使用cars数据,所需的输出为:

tribble(
~speed.summary,        ~dist.summary, 
mysummary(cars$speed), mysummary(cars$dist)
)

# A tibble: 1 x 2
  speed.summary    dist.summary    
  <list>           <list>          
1 <tibble [5 x 1]> <tibble [2 x 1]>    

当然,实际数据还有更多列......

建议?

2 个答案:

答案 0 :(得分:4)

我们可以使用

res <- cars %>%
        summarise_all(funs(summary = list(mysummary(.)))) %>% 
        as.tibble
res
# A tibble: 1 x 2
#   speed_summary    dist_summary    
#  <list>           <list>          
#1 <tibble [3 x 1]> <tibble [2 x 1]>

res$speed_summary
#[[1]]
# A tibble: 3 x 1
#   value
#* <dbl>
#1  4.00
#2 12.0 
#3 15.0 

答案 1 :(得分:0)

这是你的想法吗?

# loading necessary libraries and the data
library(tibble)
library(purrr)
#> Warning: package 'purrr' was built under R version 3.4.2
data(cars)

# custom summary function (only for numeric variables)
mysummary <- function(x) {
  if (is.numeric(x)) {
    df <- quantile(x)[1:sample(1:5, 1)]
    df <- tibble::as.tibble(df)
  }
}

# return a list of different sized tibbles depending on the data
purrr::map(.x = cars, .f = mysummary)
#> $speed
#> # A tibble: 5 x 1
#>   value
#> * <dbl>
#> 1  4.00
#> 2 12.0 
#> 3 15.0 
#> 4 19.0 
#> 5 25.0 
#> 
#> $dist
#> # A tibble: 1 x 1
#>   value
#> * <dbl>
#> 1  2.00

reprex package创建于2018-01-27(v0.1.1.9000)。