[R] breaking out of a loop from within a function
Christopher Marcum
cmarcum at uci.edu
Mon Nov 24 03:02:36 CET 2008
Hello useRs,
I would like to break out of a for loop from within a function upon
some user input. For example, a user hits "Cancel" from a tcl widget
called iteratively within a for loop. The for loop then breaks at the
current iteration.
I can only seem to get break and stop to work at the top-level.
The following example would make this more clear:
#start tcltk
require(tcltk)
#Define a R+tlk/tk environment from which to obtain user input
checktext<-function(event,anchor,text1,text2){
fun.env<-environment()
hdr<-paste("You are coding disputed event:",event, "\n\t","located
at anchor:",anchor,sep=" ")
a<-0
OnAdvance <- function()
{
assign("a",tclvalue(tt.acceptval),envir=fun.env)
tkdestroy(tt)
}
OnStop <- function()
{
#Here is where the break function is defined for tcl
break
tkdestroy(tt)
}
tt <- tktoplevel()
tt.header<- tktext(tt,bg="lightpink",fg="black",width=50,height=5)
tt.text1 <-
tktext(tt,bg=gray(.05),font="courier",fg="lightblue",width=50,height=25)
tt.text2 <-
tktext(tt,bg=gray(.05),font="courier",fg="lightgreen",width=50,height=25)
tt.accept<-tkcheckbutton(tt,text="Accept Code",width=10)
tt.acceptval<-tclVar("0")
tkconfigure(tt.accept,variable=tt.acceptval)
tt.advance<-tkbutton(tt,text="Advance
Recon",command=OnAdvance,bg="green")
tt.stop<-tkbutton(tt,text="Stop Recon",command=OnStop,bg="red")
tkinsert(tt.header,"end",hdr)
tkinsert(tt.text1,"end",text1)
tkinsert(tt.text2,"end",text2)
tkgrid(tt.header,column=1,row=1,columnspan=3)
tkgrid(tt.text1,column=2,row=2)
tkgrid(tt.text2,column=3,row=2)
tkgrid(tt.accept,column=2,row=4,rowspan=3)
tkgrid(tt.advance,column=3,row=4,rowspan=3,sticky="w")
tkgrid(tt.stop,column=3,row=4,sticky="e")
tkfocus(tt)
tkwait.window(tt)
a
}
#Some arbitrary text to code
event<-"blup"
anchor<-"1234"
text1<-"Batman struck the Riddler with his gauntlet. KAPOW!<anchor=1234>"
text2<-"Batman struck the Riddler with his gauntlet. KAPOW!"
#Ideally, if the user hits "Cancel" the loop would end on the current
ith iteration and return to the console
output<-NULL
for(i in 1:3){
output[i]<-checktext(rep(event,3)[i],rep(anchor,3)[i],text1,text2)
}
Regards,
Christopher Marcum
Department of Sociology / Cal(it)^2
University of California - Irvine
More information about the R-help
mailing list