R purrr 包map() 与 pmap() 区别

问题描述 投票:0回答:1

我试图了解以下用例中

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”

但他们不是。

r purrr
1个回答
0
投票

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
的并行列处理能力。

© www.soinside.com 2019 - 2024. All rights reserved.