ghb
ghb

Reputation:

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?

Upvotes: 79

Views: 263954

Answers (4)

Hossein AZ
Hossein AZ

Reputation: 21

You can try this:

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

Upvotes: 2

Leo Brueggeman
Leo Brueggeman

Reputation: 2521

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

Upvotes: 4

DKK
DKK

Reputation: 1920

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

More info here or even here!

Upvotes: 123

cbeleites
cbeleites

Reputation: 14093

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)
    

Upvotes: 18

Related Questions