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

Duncan Murdoch murdoch at stats.uwo.ca
Tue Jan 15 19:50:52 CET 2008

On 1/15/2008 1:18 PM, Bruno Jesus wrote:
> 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)
> }

You can do this sort of thing fairly easily with tcltk (and presumably 
with other GUI packages too, but I don't know how).  You'll need to read 
the TCL/TK manual (which is distributed with at least the Windows 
version of R) and translate those instructions into the R syntax.  For a 
  vaguely related example, see the tkcanvas demo in the tcltk package; 
for another, see the spin3d or spinControl functions in the tkrgl package.

Duncan Murdoch

More information about the R-help mailing list