-3

I want to using while loop in R.

I want to repeat loop until evt>1 and cpr>0, but it doesn't work.

work_f is function of generating numbers.

if((evt>1)&&(cpr>0)){
work<-work[order(work$z),]
obs<-c(1:length(work$z))
work<-cbind(work,obs)
  } else {
 while((evt>1)&&(cpr>0)) {
  j<-j+1
  seed<-settings*1000+h+j     

  work_f(studysize = studysize,beta=beta,cutpoint = cutpoint,settings = settigns,p=p,alpha = alpha)

  evt<-data.frame(ftable(work$event))
  evttr<-data.frame(evt=numeric(1),cpr=numeric(1),csr=numeric(1))
  if (p==0) {
    evttr$evt<-evt$Freq[1]; evttr$cpr<-evt$Freq[2]; evttr$csr<-0
  }else {
    evttr$evt<-evt$Freq[2]; evttr$cpr<-evt$Freq[3]; evttr$csr<-evt$Freq[1]
  }
  evttr[is.na(evttr)]<-0
  evt<-as.numeric(evttr$evt); cpr<-as.numeric(evttr$cpr)

  if((evt>1)&&(cpr>0)){
    work<-work[order(work$z),]
    obs<-c(1:length(work$z))
    work<-cbind(work,obs)
  }
 }
} 

What's wrong?

k_kim
  • 1
  • What is the problem? Do you get an error? The wrong result? – Guillaume F. Jan 03 '16 at 08:25
  • Please consider reading up on [ask] and how to produce a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Heroka Jan 03 '16 at 08:32
  • 2
    The `((evt>1)&&(cpr>0))` condition must be `FALSE` and `TRUE` at the same time to enter the `while` loop. – nicola Jan 03 '16 at 09:04

1 Answers1

3

Most likely your problem is in the head of your while loop as it can never enter your while loop. This becomes visible if I remove most of your code

evt = 0
cpr = 0
if ((evt > 1) && (cpr > 0)) {
  cat("a")
} else {
  #due to the if (evt > 1) && (cpr > 0)==false
  #hence the loop is never entered
  while ((evt > 1) && (cpr > 0)) {
    cat("b")
  }
} 

I addition you duplicated the code of the if-true body.

if ((evt > 1) && (cpr > 0)) {
      work <- work[order(work$z),]
      obs <- c(1:length(work$z))
      work <- cbind(work,obs)
}

At the end of the loop. I assume that once you fixed the above problem you can re-factor your code that this part occurs only once.

CAFEBABE
  • 3,983
  • 1
  • 19
  • 38