Reputation: 1339
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
?
Upvotes: 2
Views: 855
Reputation: 269481
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.
Upvotes: 6