1

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

sschrass
  • 7,014
  • 6
  • 43
  • 62
  • this is really another instance of R FAQ 7.21 ... and http://stackoverflow.com/questions/6034655/r-how-to-convert-string-to-variable-name – Ben Bolker Sep 07 '12 at 19:35
  • 1
    Is there any particular reason you *need* to create new objects for every result? `a <- 100+1:10` would be just as good, and you can access the elements with very handy subsetting function `[`. It will also be significantly faster. – Roman Luštrik Sep 07 '12 at 21:58

2 Answers2

2

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))
Sacha Epskamp
  • 46,463
  • 20
  • 113
  • 131
1

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 
Alex Brown
  • 41,819
  • 10
  • 94
  • 108