79

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?

7
  • for (i in 1:10) { A[i] = d + rnorm(3)} should work. Commented May 15, 2013 at 13:29
  • 2
    that doesn't work if the variable doesn't exist yet Commented May 15, 2013 at 13:31
  • 3
    In that case, you have to use assign: for (i in 1:10){ assign(paste("A",i, sep=""), (d + rnorm(3))) } Commented May 15, 2013 at 13:34
  • doesn't work, I tried this exact code Commented May 15, 2013 at 13:36
  • 1
    Sidenote: To access variables in a loop, use get: for (i in 1:10) { print(get(paste("A", i, sep=""))) } Commented May 15, 2013 at 13:45

4 Answers 4

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

More info here or even here!

Sign up to request clarification or add additional context in comments.

8 Comments

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]
@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.
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)
Why it creates also i and nam variables?
Could I suggest adding rm(nam) at the end just for cleanup? You're a legend, thanks. This works exactly as hoped :)
|
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)
    

Comments

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]))
}

Comments

2

You can try this:

  for (i in 1:10) {
    assign(as.vector(paste0('A', i)), rnorm(3))
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.