1

For some R functions it could be useful to prompt the user to confirm that they're sure they really want to run that function. For example some function that is rarely run, is almost certain to be run interactively (i.e. with a user present), and which does irreversible things like clearing out tempfiles from the filesystem etc.

Is there a way to prompt the user for keyboard input inside an R function, such that the user has to press 'y' to continue (or 'n' to disregard, 'c' to cancel etc)

somefunction <- function() {
  
  # -- code for prompt for user confirmation --

  # some irreversible actions 
  # e.g. file.remove(...)
}
stevec
  • 41,291
  • 27
  • 223
  • 311

1 Answers1

3

Why not a simple readline function to get input from the user?

checkFunction <- function() {
  user_input <- readline("Are you sure you want to run this? (y/n)  ")
  if(user_input != 'y') stop('Exiting since you did not press y')
  print('Do something')
}

checkFunction()
#Are you sure you want to run this? (y/n)  y
#[1] "Do something"

checkFunction()
#Are you sure you want to run this? (y/n)  n
#Error in checkFunction() : Exiting since you did not press y
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213