I would like to evaluate a string, eg x1
, where x1 <- "disp"
, as the underlying value, i.e. disp
, when x1
is the loop index.
A reproducible example, using the mtcars
dataset as an example is below:
x1 <- "disp"
x2 <- "hp"
vars <- c("x1", "x2")
for (x in vars){
print(x)
}
Which gives me
#> [1] "x1"
#> [1] "x2"
Desired Outcome:
What I'm trying to get is a loop that runs these commands:
print(x1)
print(x2)
resulting in:
#> [1] "disp"
#> [1] "hp"
I recognise that the simplest solution would be to bypass x1
and x2
completely:
vars <- c("disp", "hp")
for (x in vars){
print(x)
}
But that's less helpful, as it will be very helpful to have x1
, x2
, etc, in my (unsimplified) problem.
Also, if purrr
is a better way to do something like this, instead of a loop, I'd be very interested to understand that better.
If anyone has a suggestion on a better title for the question, I will also be very interested.
Deeper Question
I simplified my question above, hoping that would be enough to get what I needed, but for context, I'm trying to do something like this:
df <- mtcars
x1 <- "disp"
x2 <- "hp"
vars <- c("x1", "x2")
for (x in vars){
lm(mpg ~ x, data = mtcars)
}
Created on 2019-07-11 by the reprex package (v0.2.1)