Passing a function argument to other arguments which are functions themselves

Assume I have an outer function that has a numeric argument and an argument which is a function itself (inner function). How can I pass the value of the numeric argument of the outer function as an argument to the inner function? Consider this toy example:

innerfun <- function(M){
 1:M
}

outerfun <- function(x, fun){
 x * fun
}

outerfun(x = 3, fun = innerfun(M = 3)) ## works
outerfun(x = 3, fun = innerfun(M = x)) ## error because innerfun can't find 'x'
outerfun(x = 3, fun = innerfun(M = get("x"))) ## doesn't work either...

So what I want to do is to call innerfun at the moment the arguments of outerfun are evaluated, using those outerfun-arguments in the call to innerfun. Any ideas or suggestions?

Upvotes: 2

Views: 3032

Answers (2)

agstudy
agstudy

Reputation: 121568

I would do something like this :

outerfun <- function(x, fun,...){
  x * fun(x,...)
}
innerfun <- function(M){
  seq_len(M) ## safer than 1:M
}
outerfun(x=3, innerfun)
[1] 3 6 9

Note that If inner function has more than one argument, it still works :

innerfun2 <- function(M,Z){
  seq(M+Z)
}
outerfun(x=3, innerfun2,Z=3)
[1]  3  6  9 12 15 18

Upvotes: 6

cogitovita
cogitovita

Reputation: 1735

Add a "global" variable:

param = 3;
outerfun(x = param, fun = innerfun(M = param))

Upvotes: 0

Related Questions