[R] questions about using loop, while and next

rex.dwyer at syngenta.com rex.dwyer at syngenta.com
Fri Mar 4 17:33:14 CET 2011


Carrie,
If your while-loop condition depends only on dt, and you don't change dt in your loop, your loop won't terminate.
The only thing inside your loop is "next".
Perhaps you mean to write:
temp=rep(NA, 10)
for(i in 1:10)
{
dt=sum(rbinom(10, 5, 0.5))
while (dt<25) {
   dt=sum(rbinom(10, 5, 0.5))
}
temp[i]=dt
}
It doesn't look like you understand "next".  Try reading the help with ?"next" -- the quotes are necessary in this case.
If you still don't understand next, you should be able to program without it with appropriate if's.
HTH
Rex


-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Carrie Li
Sent: Friday, March 04, 2011 12:10 AM
To: r-help at r-project.org
Subject: [R] questions about using loop, while and next

Hello R helpers,

I have a quick question about loop and next

In my loop, I have some random generation of data, but if the data doesn't
meet some condition, then I want it to go next, and generate data again for
next round.

# just an example..
# i want to generate the data again, if the sum is smaller than 25
temp=rep(NA, 10)
for(i in 1:10)
{
dt=sum(rbinom(10, 5, 0.5))
while (dt<25) next
temp[i]=dt
}

I also tried while(dt<25) {i=i+1}
But it doesn't seem right to me, since it running nonstop. Any solutions ?
Thanks for helps!
Carrie--

        [[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




message may contain confidential information. If you are not the designated recipient, please notify the sender immediately, and delete the original and any copies. Any use of the message by you is prohibited. 


More information about the R-help mailing list