I'm using R to build a mathematical model. I want to write a function f(a, b, g)
that takes in 3 arguments and the last one is a function. I want to know can I pass a function as an argument to another function? If this is possible, can you guys give me a simple example?
An argument when passed with a function replaces with those variables which were used during the function definition and the function is then executed with these values. Let's look at some examples for easy understanding: Example: Java.
Passing a function as an argument to the function is quite similar to the passing variable as an argument to the function. so variables can be returned from a function. The below examples describe passing a function as a parameter to another function.
It is certainly legitimate to pass a function as an argument to another function. Many elementary R functions do this. For example,
tapply(..., FUN)
You can check them by ?tapply
.
The thing is, you only treat the name of the function as a symbol. For example, in the toy example below:
foo1 <- function () print("this is function foo1!")
foo2 <- function () print("this is function foo2!")
test <- function (FUN) {
if (!is.function(FUN)) stop("argument FUN is not a function!")
FUN()
}
## let's have a go!
test(FUN = foo1)
test(FUN = foo2)
It is also possible to pass function arguments of foo1
or foo2
to test
, by using ...
. I leave this for you to have some research.
If you are familiar with C language, then it is not difficult to understand why this is legitimate. R is written in C (though its language syntax belongs to S language), so essentially this is achieved by using pointers to function. If case you want to learn more on this, see How do function pointers in C work?
Here's a really simple example from Hadley's text:
randomise <- function(f) f(runif(1e3))
randomise(mean)
#> [1] 0.5059199
randomise(mean)
#> [1] 0.5029048
randomise(sum)
#> [1] 504.245
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With