user1655499
user1655499

Reputation: 41

R: How to loop with "while" and attach variable in object name?

I need to make the following calculation:

a1= 100+1 a2 = 100+2 ... a10 = 100+10

I try to loop this as follows:

z = 1
while(z<11) {
    z = z+1
    a = 100+z
}

How can I make R store my results as a1, a2,...a10? I know I need to use "paste" and perhaps "assign", but I can't figure it out. Thank you very much for your help!

Edit: Thank you very much for your quick and helpful replies. I now also found a way to make it work (not as nice as yours though):

z = 0
while(z<10) {
    z = z+1
    x = 100+z
    assign(paste("a",z, sep=""),x)
}

Again, thank you very much!

Cheers, Chris

Upvotes: 1

Views: 859

Answers (2)

Sacha Epskamp
Sacha Epskamp

Reputation: 47551

You don't need a while loop to get that vector since you can get it with 100 + 1:10. Here is a way to assign the values using mapply:

mapply(assign,value=100+1:10,x=paste0("a",1:10),MoreArgs=list(envir=.GlobalEnv))

Upvotes: 2

Alex Brown
Alex Brown

Reputation: 42872

You don't need to use while - use setNames from the stats package:

> (function(x)setNames(x,paste(sep="","a",x)))(1:11)
 a1  a2  a3  a4  a5  a6  a7  a8  a9 a10 a11 
  1   2   3   4   5   6   7   8   9  10  11 

Upvotes: 1

Related Questions