【问题标题】:dplyr: summarise each column and return list columnsdplyr:汇总每一列并返回列表列
【发布时间】:2018-07-06 17:40:06
【问题描述】:

我希望使用自定义汇总函数来汇总 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]>    

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

建议?

【问题讨论】:

    标签: r dplyr summarize


    【解决方案1】:

    我们可以使用

    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 
    

    【讨论】:

    • 太棒了,正是我想要的!
    【解决方案2】:

    这是你的想法吗?

    # 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 日创建。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-18
      • 2016-12-29
      • 1970-01-01
      • 2016-11-15
      • 1970-01-01
      • 2021-11-14
      相关资源
      最近更新 更多