繁体   English   中英

将 purrr::pmap 与 R 的原生 pipe 运算符一起使用

[英]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
  )

pmapmutate和 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM