[R] R loops

Duncan Murdoch murdoch at stats.uwo.ca
Mon Jan 28 15:01:58 CET 2008

On 1/28/2008 8:48 AM, cvandy wrote:
> I'm a new user and am having trouble with loops.
> In the following, I'm trying to add the results of "test" and the loops are
> not working.
> I've simplified the loop.  What am I doing wrong?
> Thanks!
>> test<-numeric(20)
>> tot<-numeric(20)
>> for(i in 1:20){test[i]<-1}
>> for (i in 1:20){tot[i]<-(test[i]+tot[i])}
>> tot
>  [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

At the start numeric(20) gives you a vector of 20 zeros.  Your first 
loop changes all the values of test to 1.  Your second loop adds a one 
from test to each of the zeros in tot.

Simulating something like this by hand is a good way to spot the errors: 
  reduce the length of vector to some small number (e.g. 5), then write 
down on a piece of paper 5 slots for test, 5 for tot, and run through 
the commands as though you are R.  If you don't get what R gives at the 
end, then look at all the variables in your simulation, and identify 
where it went wrong.

Duncan Murdoch

More information about the R-help mailing list