Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we pass a function as an argument

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?

like image 561
Lin Jiayin Avatar asked Apr 04 '16 00:04

Lin Jiayin


People also ask

Can we pass a function as an argument in Java?

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.

Can we pass a function as argument of another function in JavaScript?

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.


2 Answers

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?

like image 63
Zheyuan Li Avatar answered Sep 28 '22 13:09

Zheyuan Li


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
like image 29
stevec Avatar answered Sep 28 '22 12:09

stevec