[R] 'break' function in loop
Duncan Murdoch
murdoch.duncan at gmail.com
Thu Mar 1 15:35:53 CET 2012
On 12-03-01 8:24 AM, Tsai, Pei-Chien wrote:
> Dear R helpers,
>
> I have some difficulties in using 'break' function with loop, and the followings are my script. What I try to do is (1) permute 'or' first; (2) doing t-test if this 'or' pass criteria 1 (k=1); (3) end the loop when I get 10 permutations; (4) redo everything again but this time use criteria 2 (k=2) (I have more criteria 1:n).
>
> Somehow using my script, the final dataset (results1) only contains the result from criteria 1 (twice!) but not the result from criteria 2. I guess probably I put the break function under the wrong loop but I cannot fix it. Sorry if the whole script looks quite messy, I will be very appreciate if someone can help me fix this problem or probably give me some advices to write it in a smart way.
>
>
> My attempt:
>
> controlall<- rbeta(10000,1.5,6)
> caseall<- rbeta(10000,1.6,6)
>
> results<- NULL
> results1<- NULL
> or<-vector("list",length=10)
> criteria<- matrix(data=c(1.05,1.15,1.15,1.25),ncol=2,nrow=2)
>
> for (k in 1:2) {
>
> for (i in 1:1000)
> {
> control<- sample(controlall,100)
> case<- sample(caseall,100)
> or[i]<- round(mean(case)*(1-mean(control))/(mean(control)*(1-mean(case))),digit=2)
>
> if (or[i]<criteria[k,2]&or[i]>=criteria[k,1])
> {
> group<- c(rep(1,100),rep(0,100))
> value<- c(case,control)
> ttest<- (t.test(case,control,alternative="two.sided",paired=F))$p.value
> all<- c(or[i],ttest)
> results<- rbind(results,all)
> }
> ifelse(nrow(results)==5,break,1)
Jim was right, this line doesn't make sense. Use
if(nrow(results)==5) break
instead.
Duncan Murdoch
> }
> results1<- rbind(results1,results)
> }
>
>
> Thank you so much in advance,
> Amber
>
> [[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.
More information about the R-help
mailing list