我想使用data.frames 列表获取dplyr::spread
多个列。purrr::map
想知道如何达到预期的效果吗?
library(tidyverse)
mtcars %>%
dplyr::group_by(gear, carb) %>%
dplyr::summarise_at(
.vars = names(.)[1:9]
, .funs = c("mean")
) %>%
dplyr::select(gear, carb, mpg) %>%
tidyr::spread(key = "gear", value = mpg)
# A tibble: 6 x 4
carb `3` `4` `5`
<dbl> <dbl> <dbl> <dbl>
1 1 20.3 29.1 NA
2 2 17.2 24.8 28.2
3 3 16.3 NA NA
4 4 12.6 19.8 15.8
5 6 NA NA 19.7
6 8 NA NA 15
mtcars %>%
dplyr::group_by(gear, carb) %>%
dplyr::summarise_at(
.vars = names(.)[1:9]
, .funs = c("mean")
) %>%
dplyr::select(gear, carb, disp) %>%
tidyr::spread(key = "gear", value = disp)
# A tibble: 6 x 4
carb `3` `4` `5`
<dbl> <dbl> <dbl> <dbl>
1 1 201. 84.2 NA
2 2 346. 121. 108.
3 3 276. NA NA
4 4 416. 164. 351
5 6 NA NA 145
6 8 NA NA 301
现在我想使用单个命令执行这两个过程purrr::map
。想知道如何实现这一点。
mtcars %>%
dplyr::group_by(gear, carb) %>%
dplyr::summarise_at(
.vars = names(.)[1:9]
, .funs = c("mean")
) %>%
dplyr::select(gear, carb, mpg, disp) %>%
purrr::map(.f = ~ tidyr::spread(data = mtcars, key = "gear", value = .x))