How to wait for a keypress in R?

RKeypressWaitReadlineReadkey

R Problem Overview


I want to pause my R script until the user presses a key.

How do I do this?

R Solutions


Solution 1 - R

As someone already wrote in a comment, you don't have to use the cat before readline(). Simply write:

readline(prompt="Press [enter] to continue")

If you don't want to assign it to a variable and don't want a return printed in the console, wrap the readline() in an invisible():

invisible(readline(prompt="Press [enter] to continue"))

Solution 2 - R

Method 1

Waits until you press [enter] in the console:

cat ("Press [enter] to continue")
line <- readline()

Wrapping into a function:

readkey <- function()
{
	cat ("Press [enter] to continue")
    line <- readline()
}

This function is the best equivalent of Console.ReadKey() in C#.

Method 2

Pause until you type the [enter] keystroke on the keyboard. The disadvantage of this method is that if you type something that is not a number, it will display an error.

print ("Press [enter] to continue")
number <- scan(n=1)

Wrapping into a function:

readkey <- function()
{
	cat("[press [enter] to continue]")
    number <- scan(n=1)
}

Method 3

Imagine you want to wait for a keypress before plotting another point on a graph. In this case, we can use getGraphicsEvent() to wait for a keypress within a graph.

This sample program illustrates the concept:

readkeygraph <- function(prompt)
{
	getGraphicsEvent(prompt = prompt, 
                 onMouseDown = NULL, onMouseMove = NULL,
                 onMouseUp = NULL, onKeybd = onKeybd,
                 consolePrompt = "[click on graph then follow top prompt to continue]")
	Sys.sleep(0.01)
	return(keyPressed)
}

onKeybd <- function(key)
{
	keyPressed <<- key
}

xaxis=c(1:10) # Set up the x-axis.
yaxis=runif(10,min=0,max=1) # Set up the y-axis.
plot(xaxis,yaxis)

for (i in xaxis)
{
	# On each keypress, color the points on the graph in red, one by one.
	points(i,yaxis[i],col="red", pch=19)
	keyPressed = readkeygraph("[press any key to continue]")
}

Here you can see the graph, with half of its points colored, waiting for the next keystroke on the keyboard.

Compatibility: Tested under environments use either win.graph or X11. Works with Windows 7 x64 with Revolution R v6.1. Does not work under RStudio (as it doesn't use win.graph).

enter image description here

Solution 3 - R

Here is a little function (using the tcltk package) that will open a small window and wait until you either click on the continue button or press any key (while the small window still has the focus), then it will let your script continue.

library(tcltk)

mywait <- function() {
    tt <- tktoplevel()
    tkpack( tkbutton(tt, text='Continue', command=function()tkdestroy(tt)),
        side='bottom')
    tkbind(tt,'<Key>', function()tkdestroy(tt) )

    tkwait.window(tt)
}

Just put mywait() in your script anywhere that you want the script to pause.

This works on any platform that supports tcltk (which I think is all the common ones), will respond to any key press (not just enter), and even works when the script is run in batch mode (but it still pauses in batch mode, so if you are not there to continue it it will wait forever). A timer could be added to make it continue after a set amount of time if not clicked or has a key pressed.

It does not return which key was pressed (but could be modified to do so).

Solution 4 - R

R and Rscript both send '' to readline and scan in non-interactive mode (see ? readline). The solution is to force stdin using scan.

cat('Solution to everything? > ')
b <- scan("stdin", character(), n=1)

Example:

$ Rscript t.R 
Solution to everything? > 42
Read 1 item

Solution 5 - R

The function keypress() from the package keypress reads a single key stroke instantly, without having to hit enter.

However, it only works in the Unix/OSX terminal or Windows command line. It does not work in Rstudio, the Windows R GUI, an emacs shell buffer etc.

Solution 6 - R

This answer is similar to that of Simon's, but does not require extra input other than a newline.

cat("Press Enter to continue...")
invisible(scan("stdin", character(), nlines = 1, quiet = TRUE))

Using nlines=1 instead of n=1, the user can simply press enter to continue the Rscript.

Solution 7 - R

A way of doing it (kinda, you have to press a button rather than a key, but close enough) is to use shiny:

library(shiny)

ui     <- fluidPage(actionButton("button", "Press the button"))
server <- function(input, output) {observeEvent(input$button, {stopApp()})}

runApp(shinyApp(ui = ui, server = server))

print("He waited for you to press the button in order to print this")

To my experience, this has a unique characteristic: even if you ran a script that had code written following the runApp function, it will not run until you've pressed the button in the app (button that stops the apps from inside using stopApp).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionContangoView Question on Stackoverflow
Solution 1 - RnnnView Answer on Stackoverflow
Solution 2 - RContangoView Answer on Stackoverflow
Solution 3 - RGreg SnowView Answer on Stackoverflow
Solution 4 - RSimon A. EugsterView Answer on Stackoverflow
Solution 5 - RsiesteView Answer on Stackoverflow
Solution 6 - Ruser5068121View Answer on Stackoverflow
Solution 7 - RSébastien WoutersView Answer on Stackoverflow