Function parameter as argument in an R function
In R, a function can be provided as a function argument. The syntax matches the one of non-function objects.
Here is an example function.
myfun <- function(x, FUN) {
FUN(x)
}
This function applies the function FUN
to the object x
.
A few examples with a vector including the numbers from 1 to 10:
vec <- 1:10
> myfun(vec, mean)
[1] 5.5
> myfun(vec, sum)
[1] 55
> myfun(vec, diff)
[1] 1 1 1 1 1 1 1 1 1
This is not limited to built-in functions, but works with any function:
> myfun(vec, function(obj) sum(obj) / length(obj))
[1] 5.5
mymean <- function(obj){
sum(obj) / length(obj)
}
> myfun(vec, mymean)
[1] 5.5
you can also store a function name as a character variable, and call it with do.call()
> test = c(1:5)
> do.call(mean, list(test))
[1] 3
>
> func = 'mean'
> do.call(func, list(test))
[1] 3