Search code examples
rstringfunctionevaluate

Evaluating a function pointed to by a string in R


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.


Solution

  • 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