我试图了解以下用例中
purrr::map()
与 purrr::pmap()
的行为。我期待相同的结果,但看起来 purrr::map()
仅在列表中迭代一次。
# using pmap
pmap(.l = list(x = c(1,6)) ,.f = function(x) {substr("costcopull",x,x-1+5)})
# result
[[1]]
[1] "costc"
[[2]]
[1] "opull"
# using map
map(.x = list(x = c(1,6)) ,.f = function(x) {substr("costcopull",x,x-1+5)})
$x
[1] "costc"
我期望两个结果是相同的,因为该函数具有单数输入“x”
但他们不是。
map
将函数应用于向量/列表的每个元素。c(1,6)
substr
不是向量化函数,因此它只会使用向量的第一个索引:1
x <- c(1,6)
substr("abcdef",x,1)
[1] "a"
pmap
对于数据帧(向量列表)逐行并行处理列特别有用:
df <- data.frame(x = c(1,3),y=c(2,4))
dput(df)
#> structure(list(x = c(1, 3), y = c(2, 4)), class = "data.frame", row.names = c(NA,
#> -2L))
pmap(df, \(x,y) paste(x,y))
#> [[1]]
#> [1] "1 2"
#>
#> [[2]]
#> [1] "3 4"
当您提供单个元素列表作为参数时,
pmap
会逐行浏览此单列:
pmap(.l = list(x = c(1,3)) ,.f = function(x) {x})
#[[1]]
#[1] 1
#[[2]]
#[1] 3
总而言之,正如@Darren Tsai所指出的,直接输入
c(1,6)
到map
似乎就是你要找的。pmap
的并行列处理能力。