【问题标题】:Use function arguments in purrr::possibly otherwise在 purrr::possively 中使用函数参数
【发布时间】:2019-09-24 15:05:19
【问题描述】:

有没有办法在purrr::possibly()otherwise 参数中使用传递给原始函数的参数?

例如(这是一个愚蠢的玩具示例——真正的代码涉及在受密码保护的门户后面的网页抓取):

library(tidyverse)
library(purrr)

foo  <- tibble(x = 1:3, y = 1:3)

toyfunction  <- function(x, df = foo) {
   df[x, x] %>%
     mutate(indexed_at = x)
}

# gives an error once we get over 3
map(1:6, toyfunction)

# so, let's make it safe
possiblyversion  <- possibly(toyfunction, otherwise = 12345) 

# this works, but get confusing & inconsistent (I couldn't use map_dfr() if I wanted to!)
map(1:6, possiblyversion)

# ideally, something like this would be possible
idealpossible  <- possibly(
     toyfunction(x, df = foo)
   , otherwise = tibble(x = NA, y = NA, indexed_at = x)
)

# so we get results like this:
idealpossible(6)

# A tibble: 1 x 2
      x          y    indexed_at
  <int>      <int>         <dbl>
     NA         NA            6

保持作业运行并返回一致的结果比捕获错误等更重要,这就是我没有考虑safely()quietly() 的原因。

有没有办法在otherwise 结果中使用原始函数参数?

【问题讨论】:

    标签: r tidyverse purrr


    【解决方案1】:

    由于safely()possibly() 只允许otherwise= 使用静态值,因此您需要编写自己的包装器。这是一个粗略的例子,说明这可能是什么样子

    possibly2 <- function(.f, otherwise=NULL) {
      function(...) {
        tryCatch({
          .f(...)  
        }, error = function(e) otherwise(...))
      }
    }
    
    wrapped_toy <- possibly2(
      toyfunction, 
      function(x, df) tibble(x = NA, y = NA, indexed_at = {{x}})
    )
    map_dfr(1:6, wrapped_toy)
    

    这不会做任何真正的错误检查,但基本上你可以将一个函数传递给otherwise(),它将使用与基本函数相同的参数被调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-03
      • 2021-06-21
      • 2021-06-09
      • 1970-01-01
      • 2017-07-19
      • 2022-01-23
      • 1970-01-01
      • 2020-10-08
      相关资源
      最近更新 更多