Reputation: 61
Using R. Is there a way that I can give R any text string and it will treat it like a formula?
An example says it all.
a <- 1
b <- 2
c <- 3
d <- 4
What if I had to do this all the way up to z?
In R we can write:
letters[1]
This gives us an "a"
So what about something like this: (It doesn't work but I'd like to do something like this)
for (i in 1:4) {
letters[i] <- i
}
There's the as.formula
function but that's only good for formulas like a ~ b + c
.
Thanks.
Upvotes: 1
Views: 75
Reputation: 121568
If you want to evaluate a text :
eval(parse(text="a<-1"))
But if you want to initialize many variables, you can create a named list and convert it to a separate variables (attach each components to the global environment) using list2env
, but I would highly recommend that you keep your variables in the same list.
xx <- letters[1:5]
list2env(setNames(seq_along(xx), xx), .GlobalEnv)
Upvotes: 2