【发布时间】: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 结果中使用原始函数参数?
【问题讨论】: