[R] trouble with exiting loop if condition is met

Kelly Wu kekwu @ending from ucd@vi@@edu
Thu Jun 28 21:53:44 CEST 2018


I am working on a clinical trial simulation with two groups, treatment and
placebo, and the outcome is dichotomous (recovery or no recovery) . I would
like to stop my loop if either of my conditions are met:

1) futility - there are no responses to treatment in the treatment group.
2) the p-value is significant (<=0.01).

The problem I am having is my loop continues to run 10,000 times even though
I am sure that at least one of the conditions are met in some instances. It
appears the main problem is that my if loop is not adequately filtering the
conditions I specified in it.

library(magrittr)
library(dplyr)

nSims <- 10000 #number of simulated experiments
futility1 <-numeric(nSims) #set up empty container for all simulated
futility
futility2 <-numeric(nSims) #set up empty container for all simulated
futility

significant1 <-numeric(nSims) #set up empty container for all simulated
significance
significant2 <-numeric(nSims) #set up empty container for all simulated
significance

for(i in 1:nSims){ #for each simulated experiment
 # Year 1

 # p1<-response in controls
 # p2<-response in treated
 # Generating random deviates from a Uniform(0,1) distribution
 control.year1<-(runif(16, min = 0, max = 1))
 treat.year1<-(runif(16, min = 0, max = 1))

 #Generating dichotomous response variables for each group
 control.respond1<-ifelse(control.year1<=0.05,1,0)
 treat.respond1<-ifelse(treat.year1<=0.30,1,0)

 #Summing number of responses from each group
 control.no1<-sum(control.respond1==0)
 control.yes1<-sum(control.respond1==1)
 treat.no1<-sum(treat.respond1==0)
 treat.yes1<-sum(treat.respond1==1)

 #Perform the Fisher's exact test (one sided) with p<0.01

fisher<-matrix(c(control.no1,control.yes1,treat.no1,treat.yes1),nrow=2,ncol=2)
 f<-fisher.test(fisher,alternative = "greater") 

 #year 2
 if (f$p.value>0.01 && treat.yes1!=0){
   # Generating random deviates from a Uniform(0,1) distribution
   control.year2<-(runif(16, min = 0, max = 1))
   treat.year2<-(runif(16, min = 0, max = 1))

   #Generating dichotomous response variables for each group
   control.respond2<-ifelse(control.year2<=0.05,1,0)
   treat.respond2<-ifelse(treat.year2<=0.30,1,0)

   #Summing number of responses from each group
   control.no2<-sum(control.respond2==0)
   control.yes2<-sum(control.respond2==1)
   treat.no2<-sum(treat.respond2==0)
   treat.yes2<-sum(treat.respond2==1)

   #Perform the Fisher's exact test (one sided) with p<0.01

fisher2<-matrix(c(control.no2,control.yes2,treat.no2,treat.yes2),nrow=2,ncol=2)
   f2<-fisher.test(fisher2,alternative = "greater") 
 }


 significant2[i]<-ifelse(f2$p.value<0.01,1,0)
 futility2[i]<-ifelse(treat.yes2==0,1,0)
}

table(significant1)
table(futility1)

table(significant2)
table(futility2)



More information about the R-help mailing list