dplyr:汇总每列并返回列表列 [英] dplyr: summarise each column and return list columns
本文介绍了dplyr:汇总每列并返回列表列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望用自定义汇总功能汇总小标题中的每一列,该汇总函数将根据数据返回不同大小的小标题。
I am looking to summarize each column in a tibble with a custom summary function that will return different sized tibbles depending on the data.
假设我的汇总函数是
mysummary <- function(x) {quantile(x)[1:sample(1:5, 1)] %>% as_tibble}
它可以这样应用于一列:
It can be applied to one column as such:
cars %>% summarise(speed.summary = list(mysummary(speed)))
但是我想不出一种使用 summarise_all
(或类似方法)实现此目标的方法。
But I can't figure out a way to achieve this using summarise_all
(or something similar).
使用汽车
数据,所需的输出为:
Using the cars
data, the desired output would be:
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]>
当然,实际数据中还有更多列...
Of course the actual data has many more columns...
建议?
推荐答案
我们可以使用
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
这篇关于dplyr:汇总每列并返回列表列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文