首页 > 解决方案 > 将“pmap”输出分配给具有模式名称的数据帧

问题描述

我正在使用pmap跨多个数据帧运行相同的函数,并希望将输出列表的每个元素分配给一个具有模式名称的单独对象。但我无法弄清楚如何做到这一点。

例如,这是一个最小的示例,我正在计算三个不同变量的分位数 -

# function call 
purrr::pmap(.l = list(
  x = list(iris$Sepal.Length, mtcars$wt, anscombe$y4),
  probs = list(seq(0, 1, 0.10)),
  na.rm = list(TRUE)
),
.f = stats::quantile)

# output
#> [[1]]
#>   0%  10%  20%  30%  40%  50%  60%  70%  80%  90% 100% 
#> 4.30 4.80 5.00 5.27 5.60 5.80 6.10 6.30 6.52 6.90 7.90 
#> 
#> [[2]]
#>     0%    10%    20%    30%    40%    50%    60%    70%    80%    90% 
#> 1.5130 1.9555 2.3490 2.7730 3.1580 3.3250 3.4400 3.5550 3.7700 4.0475 
#>   100% 
#> 5.4240 
#> 
#> [[3]]
#>    0%   10%   20%   30%   40%   50%   60%   70%   80%   90%  100% 
#>  5.25  5.56  5.76  6.58  6.89  7.04  7.71  7.91  8.47  8.84 12.50

这会产生list3 个元素(每个元素都是一个数据框)。而不是得到这个list作为回报,我想自动将每个元素分配给一个具有模式名称的对象(例如,[[1]]as df_1[[2]]as df_2[[3]]asdf_3等)。(我知道这个assign功能,但我不知道如何将它与purrr.)

标签: rtidyversepurrr

解决方案


You can do it with map2:

library(purrr)
res <- pmap(.l = list(
    x = list(iris$Sepal.Length, mtcars$wt, anscombe$y4),
    probs = list(seq(0, 1, 0.10)),
    na.rm = list(TRUE)
), .f = stats::quantile)

map2(.x = paste0('df_', seq_along(res)), .y = res,
     .f = ~ assign(.x, .y, envir = .GlobalEnv))

# > df_1
#   0%  10%  20%  30%  40%  50%  60%  70%  80%  90% 100% 
# 4.30 4.80 5.00 5.27 5.60 5.80 6.10 6.30 6.52 6.90 7.90 
# > df_2
#     0%    10%    20%    30%    40%    50%    60%    70%    80%    90%   100% 
# 1.5130 1.9555 2.3490 2.7730 3.1580 3.3250 3.4400 3.5550 3.7700 4.0475 5.4240 
# > df_3
#   0%   10%   20%   30%   40%   50%   60%   70%   80%   90%  100% 
# 5.25  5.56  5.76  6.58  6.89  7.04  7.71  7.91  8.47  8.84 12.50

though I think it is better to keep the results in a list.


推荐阅读