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..."))
}
else
{
cat("Press <Enter> to continue...")
}
}


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) http://stackoverflow.com/questions/15272916/how-to-wait-for-a-keypress-in-r
 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: pause() message("works!") Now run the script on a terminal with the command: Rscript pause.R What are the results which you observe? When you press , 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") pause() f1<-readline(prompt = "enter the path of the biopsy file--") pause() 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.