gtnbz2nyt
gtnbz2nyt

Reputation: 1535

Generate new variable in R by for loop index

Hello and thanks in advance. I have a simple for loop, but the tricky part is that for every i in the counter, I'd like to generate a new variable that's indexed by i:

for (i in c(1,2,3)) {
    var_[i] <- i + 2
}

So the end result I'm trying to get is three variables var_1, var_2, var_3 equal to 3,4 and 5 respectively.

Upvotes: 1

Views: 4250

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193527

If you want to stick with your for loop and create many objects in your environment, you can just use assign:

ls()
# character(0)

for (i in c(1,2,3)) {
  assign(paste0("var_", i), i + 2)
}

ls()
# [1] "i"     "var_1" "var_2" "var_3"
var_1
# [1] 3
var_2
# [1] 4
var_3
# [1] 5

(There may be a better way to do whatever it is you're trying to do though...)

Upvotes: 2

Related Questions