0

I am trying to assign some values to some variable names in R. For example,

var1 = "old_string1"
var2 = "old_string2"

Now I have a list of new values I would like to assign to var1 and var2. Say c("new_string1", "new_string2"). How would I, using a loop, assign the values in the string to var1 and var2?

MrFlick
  • 195,160
  • 17
  • 277
  • 295
Prabesh
  • 40
  • 5
  • 2
    What you are describing seems like a bit of an anti-pattern in R. Having names of variables as strings gets really messy because you have to go through `get()/assign()` to work with those values. It's much easier in R to use named lists of values. Maybe it would be more clear if you gave a more complete [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). I'm not exactly sure what your inputs and outputs are here. – MrFlick Jul 06 '21 at 21:25

1 Answers1

0

Use assign():

values <- c("new_string1", "new_string2")

for (i in seq(along = values))
  assign(paste0("var", i), values[i])
eastclintw00d
  • 2,250
  • 1
  • 9
  • 18