6

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Lin Jiayin
  • 499
  • 1
  • 6
  • 11
  • 3
    Functionals? http://adv-r.had.co.nz/Functionals.html – slamballais Apr 04 '16 at 00:10
  • Yes. See the Examples section of `?optim` and `?integrate` for some R functions that accept other functions as arguments. – G. Grothendieck Apr 04 '16 at 00:17
  • 2
    This question is an absolutely valid question, is not unfocussed at all (it contains a question and example), and should not be closed. There is already one good answer, but given it's a complex topic, other answers may also offer valuable information/examples – stevec Jul 02 '20 at 05:21

2 Answers2

13

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?

xihh
  • 169
  • 2
  • 12
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
3

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
stevec
  • 41,291
  • 27
  • 223
  • 311