How to pass parameters to a function that is wrapped inside "possibly"

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>

I'm not on computer to confirm but I think may be overcomplicating. Try

my_fun_possibly <- purrr::possibly(
    my_fun,
    otherwise = 0
  )

Thanks - that's it.
I hadn't twigged that possibly would simply pass the arguments on (presumably via an invisible ... sort of thing).

@francisbarton ,

I think you are right. See

library(purrr)
my_fun <- function(a, b) {
  sum(a, b)
}

my_fun_possibly <- purrr::possibly(
  ~ my_fun(.x, .y),
  otherwise = 0
)

my_fun_possibly(3.1, 4.2) 
#> [1] 7.3
Created on 2021-07-21 by the reprex package (v2.0.0)

Thanks. Your use of the anonymous function within possibly is not needed though, just the bare function is fine. Though maybe your way gives scope to do more with the function.

library(purrr)
my_fun <- function(a, b) {
  sum(a, b)
}

my_fun_possibly <- purrr::possibly(
  my_fun,
  otherwise = 0
)

my_fun_possibly(3.1, 4.2)
#> [1] 7.3

Created on 2021-07-21 by the reprex package (v2.0.0)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.