将 `pmap` 输出分配给具有模式名称的数据帧 [英] assigning `pmap` output to dataframes with pattern names

查看:69
本文介绍了将 `pmap` 输出分配给具有模式名称的数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 pmap 在多个数据帧上运行相同的函数,并希望将输出列表的每个元素分配给一个名称具有模式的单独对象.但我不知道该怎么做.

I am using pmap to run the same function across multiple dataframes and wish to assign each element of the output list to a separate object with a name that has a pattern. But I can't figure out how to do this.

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

For example, here is a minimal example where I am computing quantiles for three different variables-

# 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

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

This produces a list of 3 elements (each of which is a dataframe). Instead of getting this list in return, I want to automatically assign each element to an object with a pattern name (e.g., [[1]] as df_1, [[2]] as df_2, [[3]] as df_3, etc.). (I know about the assign function, but I can't figure out how to combine it with purrr.)

推荐答案

你可以用 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.

这篇关于将 `pmap` 输出分配给具有模式名称的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆