Hi, I am experimenting with purrr::possibly
and I am stuck and in need of help!
I've got a function that calls an API, and I want to wrap my function in possibly
, but I also need to pass some parameters to the wrapped function.
In the possibly
docs, which are quite sparse, it only shows a bare function being wrapped, not one with parameters like (a, b)
.
With my real-life situation, I am getting the error
Error: Can't convert a logical vector to function
which I can see from here would be a result of calling the function as the .f
parameter to possibly
(ie the "logical vector" is the output of the function, not the function itself), rather than just naming the function. But then I am stuck as to how I can pass the parameters that I need to?
As an illustration, I've simplified my situation with some toy functions in the reprex below, though this is giving me an entirely different error from the one I started with...!
Any enlightenment would be gratefully received.
library(purrr)
my_fun <- function(a, b) {
sum(a, b)
}
my_fun_possibly <- function(a, b) {
purrr::possibly(
my_fun,
# my_fun(a, b), # how do you pass parameters to your wrapped function?
otherwise = 0
)
}
sum_fun <- function() {
c(2:6, NA_integer_) %>%
sample(2) %>%
my_fun_possibly(1) # runs fine with my_fun(1), but not with possibly
}
sum_fun()
#> function (...)
#> {
#> tryCatch(.f(...), error = function(e) {
#> if (!quiet)
#> message("Error: ", e$message)
#> otherwise
#> }, interrupt = function(e) {
#> stop("Terminated by user", call. = FALSE)
#> })
#> }
#> <bytecode: 0x00000000084d97f8>
#> <environment: 0x00000000084dbd70>