Can we pass a function as an argument

It is certainly legitimate to pass a function a function argument. 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?