[英]R: Setting purrr:pmap's .l attribute in advance using the $ operator
[英]Using purrr::pmap with R's native pipe operator
pmap
的一种用途是处理可能需要map3
的情况,但 purrr 中不存在这样的purrr
。 例如:
library(tidyverse)
Z <- tibble(x = list(sample(10, size = 2), sample(10, size = 3)),
fn = c(max, min))
Z %>%
mutate(msg2 = map2_chr(x, fn, \(x,fn) paste(toString(x), '->', fn(x))), # for 2 args this is the way
msgp = pmap_chr(., \(x, fn) paste(toString(x), '->', fn(x))) # but can also do this
)
(我的示例映射了两个参数的 function,所以我实际上可以使用map2
;但想想具有三个参数的类似问题)。
我想更新我的代码以使用新的原生 R pipe |>
,但以下内容不起作用:
Z |>
mutate(msg2 = map2_chr(x, fn, \(x,fn) paste(toString(x), '->', fn(x))), # for 2 args this is the way
msgp = pmap_chr(_, \(x, fn) paste(toString(x), '->', fn(x))) # but this is an ERROR
)
将pmap
与mutate
和 R 的原生 pipe 运算符结合使用有哪些选项? 或者,在这种情况下坚持使用magritte
的 pipe ( %>%
) 是否有意义?
与..1
、 ..2
一起使用可能更好,如 arguments。在pmap
代码中, .
将采用完整的数据集列,包括创建的msg2
(因此它是 3 列而不是 2 列),但是创建的 lambda 只有两个 arguments
library(dplyr)
library(purrr)
Z |>
mutate(msg2 = map2_chr(x, fn, \(x,fn)
paste(toString(x), '->', fn(x))),
msgp = pmap_chr(across(everything()),
~ paste(toString(..1), "->", match.fun(..2)(..1))))
-输出
# A tibble: 2 × 4
x fn msg2 msgp
<list> <list> <chr> <chr>
1 <int [2]> <fn> 9, 3 -> 9 9, 3 -> 9
2 <int [3]> <fn> 6, 2, 9 -> 2 6, 2, 9 -> 2
或者,如果使用 OP 的代码并稍作修改以仅包含 x、fn 列
Z |>
mutate(msg2 = map2_chr(x, fn, \(x,fn)
paste(toString(x), '->', fn(x))), # for 2 args this is the way
msgp = pmap_chr(across(c(x, fn)),
\(x, fn) paste(toString(x), '->', fn(x))) # but this is not an ERROR now
)
-输出
# A tibble: 2 × 4
x fn msg2 msgp
<list> <list> <chr> <chr>
1 <int [2]> <fn> 9, 3 -> 9 9, 3 -> 9
2 <int [3]> <fn> 6, 2, 9 -> 2 6, 2, 9 -> 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.