1

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
zerberus
  • 73
  • 7
  • Notice that the expression `b(i)` implies to the R interpreter that `b` is the name of a function. The paired parentheses are not used for indexing in R. – IRTFM Apr 26 '22 at 17:48

2 Answers2

1

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.

AndrewGB
  • 16,126
  • 5
  • 18
  • 49
  • 2
    You should also be giving this new useR advice about why this answer to an obvious duplicate is generally a bad strategy. – IRTFM Apr 26 '22 at 17:37
0

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)
TarJae
  • 72,363
  • 6
  • 19
  • 66