77

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?

z0nam
  • 525
  • 7
  • 19

4 Answers4

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

More info here or even here!

Community
  • 1
  • 1
DKK
  • 1,870
  • 4
  • 15
  • 22
  • thanks this works perfectly, I have a 'next step' question: what if I use this method in a loop and then I would like to use the 'i'th element of the created vector so basically Ai is A1 in the first iteration but I want to access Ai[i] – upabove May 15 '13 at 13:52
  • 2
    @ghb: then it is definitively time to go for a matrix (`A [i, i]`) or a list (`A [[i]][i]`) - much easier than `get (paste0 ("x", i))[i]`. Plus you can easily assign new values for the matrix and list versions, but for the `get`/`assign` version you'd need a temporary variable. – cbeleites unhappy with SX May 15 '13 at 13:58
  • `fortunes::fortune(236)`: *The only people who should use the assign function are those who fully understand why you should never use the assign function. -- Greg Snow R-help (July 2009)* – Uwe Jan 12 '18 at 15:01
  • Why it creates also `i` and `nam` variables? – Karol Daniluk May 18 '19 at 21:13
  • Could I suggest adding `rm(nam)` at the end just for cleanup? You're a legend, thanks. This works exactly as hoped :) – Finger Picking Good Dec 17 '19 at 17:11
  • Very helpful, thank you. `> ls() [1] "A1" "A10" "A2" "A3" "A4" "A5" "A6" "A7" "A8" "A9"` But how do I get "A01", "A02" etc.? – Gecko May 16 '20 at 12:54
  • If you are new to R, consider [using a `list` or `matrix`, as in this answer](https://stackoverflow.com/a/16566800/1048186). For most purposes, they will do what you need. – Josiah Yoder Jul 23 '21 at 19:38
  • It's an old question, but to do what @Gecko asked, you can use sprintf: `sprintf("A%02i", i)` This will write a two digit number with a leading 0 for values under 10. Also works with %03i etc – BGranato Jan 31 '22 at 23:41
18

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)
    
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
cbeleites unhappy with SX
  • 13,717
  • 5
  • 45
  • 57
4

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]))
}
Leo Brueggeman
  • 2,241
  • 1
  • 9
  • 5
2

You can try this:

  for (i in 1:10) {
    assign(as.vector(paste0('A', i)), rnorm(3))
  }
socialscientist
  • 3,759
  • 5
  • 23
  • 58
Hossein AZ
  • 21
  • 1