简体   繁体   English

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

[英]Using purrr::pmap with R's native pipe operator

One use of pmap is to deal with situations where one might want map3 , but such a function does not exist in purrr . pmap的一种用途是处理可能需要map3的情况,但 purrr 中不存在这样的purrr For example:例如:

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
  )

(where my examples maps a function of two parameters, so I can actually use map2 ; but think of the analogous problem with three parameters). (我的示例映射了两个参数的 function,所以我实际上可以使用map2 ;但想想具有三个参数的类似问题)。

I would like to update my code to use the new native R pipe |> , but the following does not work:我想更新我的代码以使用新的原生 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
  )

What are some options for using pmap with mutate and with R's native pipe operator?pmapmutate和 R 的原生 pipe 运算符结合使用有哪些选项? Or, is this one situation where it makes sense to stick to using magritte 's pipe ( %>% )?或者,在这种情况下坚持使用magritte的 pipe ( %>% ) 是否有意义?

It may be better to use with ..1 , ..2 as arguments. In the pmap code, the ...1..2一起使用可能更好,如 arguments。在pmap代码中, . will take the full dataset columns including the msg2 created (thus it is 3 columns instead of 2), but the lambda created had only two arguments将采用完整的数据集列,包括创建的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))))

-output -输出

# 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

Or if make use of the OP's code and make slight modification to include only the x, fn columns或者,如果使用 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
  )

-output -输出

# 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