dplyr:对每列进行汇总并返回列表列

4
我希望您能够用自定义汇总函数来总结tibble中的每一列,该函数将返回不同大小的tibble,具体大小取决于数据。
假设我的汇总函数如下:
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个回答

5
我们可以使用。
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
太棒了,正是我所寻找的! - crlwbm

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 (v0.1.1.9000) 在2018年1月27日创建的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接