'How to address variables with paste0?
Let's say I have vectors x_1, x_2, x_3 and a vector with their names:
x_1<-1:3
x_2<-3:5
x_3<-7:9
names<-c("x_1", "x_2", "x_3")
Is it possible to address those vectors using another vector with their names ? For example:
for (i in 1:length(names)) {
print(paste0("x_",i)/2)
}
The example doesn't work, but that's what I'd like to do. Is there any function like "as.name" or whatever that converts paste0 output into a variable name ? Thank you!
Solution 1:[1]
We may get the values of all the objects in names (it is better to use a different name as names is a base R function name) in a list with mget, divide by 2 and assign (%=% back to the names)
library(collapse)
names %=% lapply(mget(names), `/`, 2)
-output
> x_1
[1] 0.5 1.0 1.5
> x_2
[1] 1.5 2.0 2.5
> x_3
[1] 3.5 4.0 4.5
In the base R for loop, we can use assign
for (i in seq_along(names)) {
assign(paste0("x_",i), get(paste0("x_", i))/2)
}
-checking
> x_1
[1] 0.5 1.0 1.5
> x_2
[1] 1.5 2.0 2.5
> x_3
[1] 3.5 4.0 4.5
Solution 2:[2]
You can try a named list?
tibble::lst(x_1, x_2, x_3)[[names[1]]]
Then you can loop
for(i in names){
print(tibble::lst(x_1, x_2, x_3)[[i]])
}
Solution 3:[3]
I think you are looking for the eval(parse(text=...)) combination:
for (i in 1:length(names)) {
print(eval(parse(text=paste0("x_", i)))/2)
}
gives
[1] 0.5 1.0 1.5
[1] 1.5 2.0 2.5
[1] 3.5 4.0 4.5
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | akrun |
| Solution 2 | Roman |
| Solution 3 | Bas |
