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

2
  • this is really another instance of R FAQ 7.21 ... and stackoverflow.com/questions/6034655/… Commented Sep 7, 2012 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. Commented Sep 7, 2012 at 21:58

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

Comments

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 

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.