Search code examples
rvariablesnaming

name one variable according to another variable in R


I would like to name one variable according to another variable.

E.g.

a <- c(0.1,0.2)

for (i in a){

b(i) <- 1
}}



What I would like as outcome is

head(b0.1)
1
 
head(b0.2)
1

Solution

  • We can use lapply and setNames, then use list2env to save each variable to the global environment.

    list2env(lapply(setNames(a, paste0("b", a)), function(x)
      x <- 1), envir = .GlobalEnv)
    

    Another option is to use paste and assign from base R:

    a <- c(0.1,0.2)
    
    for(i in a) {
      nam <- paste0("b", i)
      assign(nam, 1)
    }
    

    Output

    head(b0.1)
    # [1] 1
    
    head(b0.2)
    # [1] 1
    

    But generally using assign is not a good idea, as detailed here.