Search code examples
rvariablespaste

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

  • 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