Change variable name in for loop using R

R

R Problem Overview


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?

R Solutions


Solution 1 - R

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

More info here or even here!

Solution 2 - R

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)
    

Solution 3 - R

Another option is using eval and parse, as in

d = 5
for (i in 1:10){
     eval(parse(text = paste('a', 1:10, ' = d + rnorm(3)', sep='')[i]))
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionghbView Question on Stackoverflow
Solution 1 - RDKKView Answer on Stackoverflow
Solution 2 - Rcbeleites unhappy with SXView Answer on Stackoverflow
Solution 3 - RLeo BrueggemanView Answer on Stackoverflow