1

I want to convert a string with a formula to an object with the type language in order to use it as a formula.

How can I accomplish this?

A short example, that shows the problem:

formula <- "(1 - sin(x^3)"
> typeof(formula)
[1] "character"

A working reference is

> typeof(quote(1 - sin(x^3)))
[1] "language"

Of course, I can't just write formula in quote:

> quote(formula)
formula

So, is there a way to convert a string in a vector to something that as the typeof language?

kabr
  • 1,249
  • 1
  • 12
  • 22
  • 1
    This question touches on this issue: https://stackoverflow.com/questions/1743698/evaluate-expression-given-as-a-string – divibisan Sep 28 '18 at 22:17

1 Answers1

5

Use parse:

y <- "1 - sin(x^3)"
p <- parse(text = y)[[1]]

p
## 1 - sin(x^3)

is.language(p)
## [1] TRUE

typeof(p)
## [1] "language"

x <- pi/4
eval(p)
## [1] 0.5342579

Note that is.language(parse(text = y)) is also TRUE but it is of type expression. On the other hand, eval(parse(text = y)) gives the same result.

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341