[R] How to interrupt a loop by pressing a key?

Bruno Jesus bmjesus at fc.ul.pt
Tue Jan 15 19:18:26 CET 2008


Hello,

Does anyone know a way of interrupting a loop by pressing a key (besides 
ctrl-c)?

My problem is the following:
I have a machine acquiring data and saving text files into a directory.
I have an R script that read those files, process them and plots the 
results.
What I would like to do is: process the data as the files appear in the 
folder (I've done that do with a loop that checks the number of files) 
and when the machine stops acquiring the data, break the loop and do 
some other calculations with the entire dataset.

I've tried a couple of solutions:
1) Setting a timer that, if certain amount of time goes by and no new 
file is created, the loop is broken and the remaining calculations 
occur. However, this solution is dependent on the machine acquiring 
time, which change with different experiments...

2) I've tried this structure:
f.loop<-function()
 {
 repeat
{
 print("initial calculations")
 switch(menu(c("go","stop")),next,break)

}
print("final calculations")

This also works but requires user intervention at each cycle to chose 
from "go" and "stop"...

So... back to the initial question. Can I break the cycle with a signal 
from the keyboard?

Something like this:

while (Idontpressthe_Y_key)
{
(1) process all files already produced
(2) wait for new files that are yet to be produced
(3) see if I am pressing key Y (go to (1) if I am not, and quit the loop 
if I am)
}


Many thanks in advance,
Bruno

------------------------
Bruno Jesus
Centro de Oceanografia
Campo Grande
1740-016 Lisboa
Portugal




More information about the R-help mailing list