Thanks for the quick answer.
My full use case is: I wrote code that applies a function one in a moving window along a vector (https://github.com/jiho/castr/blob/master/R/slide.R)*. The function to be applied in the moving window is supplied by the user. I would like to make it as robust and simple as possible: allow the user to give a name, preferably unquoted, and find a function by that name somewhere.
Indeed, using base::mean
solves the problem (because there is no masking anymore) but I'd like to avoid this if possible (i.e. make my code more complex for the user's code to be simple).
I am not sure this is completely possible. I tried to see how lapply()
(and variants) do it and this is what I observe:
> x <- 1:5
> sapply(x, FUN=mean)
[1] 1 2 3 4 5
> mean <- "bar"
> sapply(x, FUN=mean)
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'bar' of mode 'function' was not found
> sapply(x, FUN="mean")
[1] 1 2 3 4 5
> sapply(x, FUN=base::mean)
[1] 1 2 3 4 5
So even l/sapply()
gets confused there. I was wondering if, in my example above, some rlang
magic would allow to get the name of the object passed to argument fun
, in which case I would be able to use the get(name_passed_to_fun, mode="function"))
trick that lapply()
uses.
* If you read the code, you will see that my problem is actually more complicated than the example above because the user-supplied function is applied by an sapply()
call within my function, and that my function is meant to be used within mutate()
. But I suppose that if I can solve the simple problem above, then the rest should be solvable too.