name one variable according to another variable in R

Viewed 40

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
2 Answers

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.

You don`t need a loop here, What about:

paste0("b", a/10)

[1] "b0.01" "b0.02"

Or

library(stringr)
str_c("b", a/10)
Related