[R] Wait for keystroke or timeout

biostatmatt biostatmatt at gmail.com
Fri May 28 04:19:56 CEST 2010


On Thu, 2010-05-27 at 19:08 -0400, Prof. John C Nash wrote:
> I would like to have a function that would wait either until a specified timeout (in
> seconds preferably) or until a key is pressed. I've found such a function quite useful in
> other programming environments in setting up dialogs with users or displaying results,
> rather like a timed slideshow that can be speeded up by hitting a key.
> 
> Searching R-seek has led to wait() in the package 'audio', but when I try, for example,
> 
>     joe<-wait(readline("hit a key to continue"), timeout=6)
> 
> I am forced to wait the full timeout.
> 
> Probably someone has done this before and I'm just not using the right search terms.
> Suggestions welcome.
> 
> Thanks in advance.
> 
> JN
> 
> ______________________________________________
> 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.

John, 

What operating system do you use? I don't know of a general solution
to this problem (although someone else might). If you are using Linux
you can use try this

> system("read -t 1 -n 1")

where -n indicates the number of characters to read and -t specifies the
timeout in seconds. Hence, this command will wait until either 1 second
has elapsed, or 1 character has been read from the keyboard.

Also, I recently participated in a discussion on the r-devel list about
implementing a POSIX (Linux/Mac OSX) TTY (terminal) connection for R to
interface with a serial port. I am certain that a tty connection for R
could provide the functionality you are looking for, on POSIX systems.
Unfortunately this feature is currently only available as a source code
patch for R (not as an R package).

P.S. Maybe Simon (from the r-devel discussion) has the right idea, that
a tty connection should exploit the full POSIX terminal API, then input
issues like this would have easy solutions... 

-Matt



More information about the R-help mailing list