Pausing an R script: a generic pause function

Posted by Diego Assencio on 2015.04.09 under Programming (R)

If you wish to pause the execution of an R script until a user presses the Enter key, you can use the following pause function:

pause = function()
	if (interactive())
		invisible(readline(prompt = "Press <Enter> to continue..."))
		cat("Press <Enter> to continue...")
		invisible(readLines(file("stdin"), 1))

This function works both in the interactive and batch processing modes, i.e., it works regardless of whether you are working within Rstudio, an R session in the terminal or if you are executing an R script using Rscript. Readers who are interested in learning more about the difference between these modes should take a look at this article.


@humorkritik on Jun 16, 2016:
For some reason, this does not work for me. I also tried other solutions, e.g. as described on StackOverflow, to no avail.

I am able to stop the further evaluation of sourced code, or starting the next source() command if used in the top-level batch file. But I cannot continue afterwards, regardless of what I enter.

Any suggestions?

Using RStudio 0.99.896 with R version 3.2.5; x86_64-w64-mingw32/x64 (64-bit)
Diego Assencio on Jun 16, 2016:
@humorkritik: Try doing the following: create a file (say, pause.R), add the function above to it and, right below the function definition, add these two lines:


Now run the script on a terminal with the command:

Rscript pause.R

What are the results which you observe? When you press <Enter>, is the message "works!" displayed afterwards?

Kshitij Bhatnagar on Jul 27, 2018:
I want a pause till my first readline command works. ie the user enter the path before going to the next deadline command. Problem is where should I call this pause() function to do so. Help appreciated
Diego Assencio on Jul 27, 2018:
@Kshitij: I'm not sure I understand your problem. Can you please share more details about what you're trying to do?
kshitij bhatnagar on Jul 27, 2018:
d<-readline(prompt = "eneter the location of the directory")
f1<-readline(prompt = "enter the path of the biopsy file--")
f2<-readline(prompt = "enter the path of the treatment file--")

As you see if I run the above script without the pause() the command prompt overwrites the first readline and jumps to the next.
Diego Assencio on Jul 27, 2018:
@Kshitij: The problem you're encountering is likely due to the fact that readline does not wait for user input in non-interactive mode. Are you running your script using Rscript?

To fix the issue, try replacing your first readline statement with this:

cat("enter the location of the directory");
d <- readLines("stdin", 1);

Apply the same change to the subsequent readline statements. You can learn more about this topic here:
Chris on Jan 15, 2020:
Use file.choose() to have user select a file, and define the input:

data.location = file.choose() <- read.csv(data.location)