[R] R: repeat loops

Aleš Žiberna ales.ziberna at guest.arnes.si
Tue Dec 28 14:54:24 CET 2004


The mistakes in your function are:
1. the functions repeat and break do not have any arguments
2. the break function should be used insed the repear loop (or if statment 
with break function should be inside the repeat loop)

Correcting for these mistakes I corrected your function. It is at the end of 
my reply.

I also belive that it might be better to use while function.
Look at ?Control (if you haven't already)

I hope this helps!

Aleš

sim2.dat<-function(n,theta){
 u<-runif(n)
 k<-1
 P<--(1-theta)/log(theta)
 F<-P

 for(j in 1:n){
  repeat {
   P<-k*(1-theta)*P/(k+1)
   k<-k+1
   F<-F+P
   if(u[j]<F){break}
  }
 u[j]<-k
 }
 u
}



----- Original Message ----- 
From: "Michael Gray" <michael.gray at somerville.oxford.ac.uk>
To: <R-help at stat.math.ethz.ch>
Sent: Tuesday, December 28, 2004 12:47 PM
Subject: [R] R: repeat loops


To whoever this may concern

I am trying to write a repeat loop and can't make out from the documentation 
on the website how exactly to construct the repeat, break structure of the 
loop. Below is the function sim2.dat that I am trying to create, in which 
firstly I create n random uniform(0,1) numbers. From there I assign values 
to k, P and F. From then on for each random number u[j] of u, I try to set 
up a repeat loop so that if u[j]>=F I alter P, k, and F and then compare 
u[j] to F again. I want to stop the loop when u[j]<F and then assign the 
present value of k to u[j]. However my effort below seems to fail! Any help 
would be much appreciated, either with respect to repeat loops or better 
ways to conquer my problem. Thank you for your time,

Regards,

Michael Gray

R text:
sim2.dat<-function(n,theta){
+ u<-runif(n)
+ k<-1
+ P<--(1-theta)/log(theta)
+ F<-P
+ for(j in 1:n){repeat{if(u[j]>=F){P<-k*(1-theta)*P/(k+1)
+ k<-k+1
+ F<-F+P}}
+ if(u[j]<F){break(
+ repeat{if(u[j]>=F){P<-k*(1-theta)*P/(k+1)
+ k<-k+1
+ F<-F+P}})
+ u[j]<-k}}
+ u}

______________________________________________
R-help at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! 
http://www.R-project.org/posting-guide.html




More information about the R-help mailing list