r - 将“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
这会产生list
3 个元素(每个元素都是一个数据框)。而不是得到这个list
作为回报,我想自动将每个元素分配给一个具有模式名称的对象(例如,[[1]]
as df_1
,[[2]]
as df_2
,[[3]]
asdf_3
等)。(我知道这个assign
功能,但我不知道如何将它与purrr
.)
解决方案
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.
推荐阅读
- c# - 用于处理空字符串的数据注释
- excel - 在 Excel 中优化索引匹配问题的最有效方法
- reactjs - 登录 React 页面显示登录页面只有几分之一秒
- postgresql - How can I retrieve a row by uuid in Postgres database?
- c++ - C++ 中的内存映射流数据
- jquery - 如何判断页面是否一直滚动到一边
- javascript - Magento 2 最后加载 JS
- do-not-disturb - Is there a way to check the status of "do not disturb" setting in iphone or android app?
- c# - Incorrect values during JsonConver.SerializeObject using Newtonsoft.Json
- mysql - NOW() function local time retrieval for querying language design