Saroupille
Saroupille

Reputation: 629

assign a function to a variable in R

The question is in the title. I'd like to do something like this :

myfunc<- pexp
plot(function(x) myfunc(x, 0.5))

I'd like to call several functions given as parameters in my script. I'd like to use a foreach instead of a bunch of if-then-else statement :

Suppose I call my script this way :

R --slave -f script.R --args plnorm pnorm 

I'd like to do something like this :

#only get parameters after --args
args<-commandArgs(trailingOnly=TRUE)
for i in args {
    plot(function(x) i(x,param1,param2))
}

Upvotes: 2

Views: 4334

Answers (1)

Hong Ooi
Hong Ooi

Reputation: 57696

Use get to retrieve an object given a character string containing its name. In this case, you can also use getFunction, the specific version to retrieve functions.

for f in args {
     f <- getFunction(f)
     plot(function(x) f(x, param1, param2))
}

Upvotes: 6

Related Questions