0

I want to programmatically (loop or map) define the name of a variable, something like

for (i in 1:10) {

 str_c("variable_", i) <- i

}

# or

map(1:10, ~{
 str_c("variable_", .x) <- .x
 }
)

so that, in this case, I end up with 10 vars in my environment, namely: variable_1, variable_2, ..., variable_10.

but I get the following error

" Error in str_c("variable_", i) <- 1 : target of assignment expands to non-language object "

Is there a way to achieve what I want to achieve?

Cheers

arnle
  • 480
  • 4
  • 10

2 Answers2

0

For such cases specifically is assign() which takes a string as its first argument which gets converted into a variable.

for (i in 1:10) {
  assign(paste0("variable_", i), i)
}

This is the shortest way to do it in R.

Gwang-Jin Kim
  • 9,303
  • 17
  • 30
0

Here is another way

for(i in 1:10){
     .GlobalEnv[[paste0("variable_", i)]] <- i
}
Mohamed Desouky
  • 4,340
  • 2
  • 4
  • 19