Evaluating a function pointed to by a string in R

Viewed 56

Suppose I have the following:

   x <- 1:10  
   squared <- function(x) {x^2}  
   y <- "squared"

I want to be able to evaluate the function using the string defined by y. Something like eval(y), which I know is wrong, but will return

[1] 1 4 9 16 25 36 49 64 81 100

Any help is appreciated.

2 Answers

Either use match.fun

match.fun(y)(x)
#[1]   1   4   9  16  25  36  49  64  81 100

or with get

get(y)(x)
#[1]   1   4   9  16  25  36  49  64  81 100

To tell R that a given string is rather a command than a simple string, use eval(parse(text=...)).

Therefore, you could do

eval(parse(text=y))(x)

where eval(parse(text=y)) returns a function encoded in the string in y and x is the functions argument.

Moreover you could simply use match.fun, which looks whether there is a function with a specific name in the environment and grabs this function. Then then apply it to the argument x like

match.fun(y)(x)
Related