2

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.

Peter Bonate
  • 75
  • 1
  • 6
  • 1
    Another option is: `do.call(y, list(x))`. – TimTeaFan Feb 18 '21 at 21:41
  • The answers to [this question](https://stackoverflow.com/questions/13649979/what-specifically-are-the-dangers-of-evalparse) discuss why you might want to avoid `eval(parse` in favor of other alternatives that are easier to understand and debug. – eipi10 Feb 18 '21 at 21:56

2 Answers2

3

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
akrun
  • 874,273
  • 37
  • 540
  • 662
1

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)
Jonas
  • 1,760
  • 1
  • 3
  • 12