[英]Use function arguments in purrr::possibly otherwise
Is there a way to use the arguments passed to the original function in the otherwise
argument of purrr::possibly()
?有没有办法在
purrr::possibly()
的 else 参数中使用传递给原始 function 的otherwise
?
For example (this is a dumb toy example--the real code involves web scraping behind a password-protected portal):例如(这是一个愚蠢的玩具示例——实际代码涉及 web 在受密码保护的门户后面抓取):
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
Keeping the job running and returning consistent results are higher priorities than capturing the errors and whatnot, which is why I haven't considered safely()
or quietly()
.保持作业运行并返回一致的结果比捕获错误和诸如此类的优先级更高,这就是为什么我没有考虑
safely()
或quietly()
。
Is there any way to use the original function arguments in the otherwise
results?有没有办法在
otherwise
结果中使用原始 function arguments ?
Since safely()
and possibly()
only allow a static value for otherwise=
, you would need to write your own wrapper.由于 safe
safely()
和 possible possibly()
只允许 static 值 else otherwise=
,因此您需要编写自己的包装器。 Here's a crude example of what this might look like这是一个粗略的例子
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)
This doesn't do any real error checking but basically you can pass in a function to otherwise()
that will get called with the same parameters as the base function.这不会进行任何真正的错误检查,但基本上您可以将 function 传递给 else
otherwise()
,它将使用与基本 function 相同的参数调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.