Reputation: 63
I would like to know if there’s a way to convert a text to a command and execute it. Here’s the concerned part of the script I’m working on:
Var_name<- as.character(data_list[1,1])
U4005
(data_list
contains just names of vectors in a bigger dataframe called vectors
)
Comm<-paste(Var_name,”<-“,”vectors$”,Var_name)
Comm
“U4005<-vectors$U4005”
Upvotes: 0
Views: 783
Reputation: 66834
This seems a strange thing to do, but I think you are better off using assign
rather than creating "interactive" commands to parse.
assign(Var_name,vectors[[Var_name]])
This way you can loop over your names to pull things out quite easily. You just need to specify that it is the global environment to assign to.
x <- data.frame(a=1:3,b=letters[1:3])
ls()
[1] "x"
invisible(sapply(names(x),function(y) assign(y,x[[y]],.GlobalEnv)))
ls()
[1] "a" "b" "x"
a
[1] 1 2 3
b
[1] a b c
Levels: a b c
Upvotes: 2
Reputation: 20329
The following code should work:
e <- "a <- 1"
eval(parse(text = e))
a
# [1] 1
Does it help?
Upvotes: 2