dplyr:汇总每一列并 return 列出列
dplyr: summarise each column and return list columns
我希望使用自定义汇总函数来汇总小标题中的每一列,该函数将根据数据 return 不同大小的小标题。
假设我的汇总函数是这样的:
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]>
当然实际数据还有很多列...
建议?
我们可以使用
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
这是你想要的吗?
# 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 创建于 2018-01-27
包 (v0.1.1.9000).
我希望使用自定义汇总函数来汇总小标题中的每一列,该函数将根据数据 return 不同大小的小标题。
假设我的汇总函数是这样的:
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]>
当然实际数据还有很多列...
建议?
我们可以使用
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
这是你想要的吗?
# 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 创建于 2018-01-27 包 (v0.1.1.9000).