[Solved] [R] Convert character to command

TheEcologist

Global Moderator
He guys,

I've been wondering if this is in someway possible in R. Maybe someone here knows.

Lets say you have a set of R-commands saved as characters, how do you convert these to commands?

Code:
# lets say we have the following
a="rep(c("A", "B"),each=2)"
# its classified as a character
class(a)
# a function like ?eval wil only return it
eval(a)
# I know you can reproduce what I want this with
eval(call("rep",c("A","B"),each=2))
# but I have the command stored in full, and then of course it does not work
eval(call(a))
# using Substring and strsplit only works if each stored command was identical
# which defeats the purpose for me
# a function like ?get will return a object but I cant get it to work with functions in the
# base package
get("a", pos=baseenv())
Anybody know a trick to do this? It will make my day.

Last edited:

Dason

Re: [R] Convert character to command

I've needed to do the same type of thing. I should probably look more into why it works but this is what I've found
Code:
commands <- "a <- rep(c(1,2,4),4)"
eval(parse(text = commands))
a

TheEcologist

Global Moderator
Re: [R] Convert character to command

And here I've been thinking parse only works with an outside file!

Thanks Dason. That makes my day.
:tup: