Change variable name in for loop using R


I have a for loop:

for (i in 1:10){ Ai=d+rnorm(3)}

What I would like to do is have A1, A2,A3...A10 and I have the variable i in the variable name.

It doesn't work this way, but I'm probably missing some small thing. How can I use the i in the for loop to assign different variable names?

This question is tagged with r

~ Asked on 2013-05-15 13:27:07

The Best Answer is


d <- 5
for(i in 1:10) { 
 nam <- paste("A", i, sep = "")
 assign(nam, rnorm(3)+d)

More info here or even here!

~ Answered on 2013-05-15 13:46:42


You could use assign, but using assign (or get) is often a symptom of a programming structure that is not very R like. Typically, lists or matrices allow cleaner solutions.

  • with a list:

    A <- lapply (1 : 10, function (x) d + rnorm (3))
  • with a matrix:

    A <- matrix (rep (d, each = 10) + rnorm (30), nrow = 10)

~ Answered on 2013-05-15 13:46:28

Most Viewed Questions: