Make readline wait for input in R

If you want to do this in interactive mode then you already have answers but not for use with Rscript. For that instance you need to send messages to the console with cat:

If this test file is named ‘prompt.r’ and is in the directory where you are working in a system console session:

cat("a string please: ");
a <- readLines("stdin",n=1);
cat("You entered")
 str(a);
cat( "\n" )

Then you can run it from the command line as

$ Rscript prompt.r

If you want an all-purpose script then this would run your script under interactive conditions and my script for non-interactive ones:

if (interactive() ){raw <- 
             readline("TRUE or FALSE -- this is a validation run: ")

                if (raw == "F" | raw == "FALSE" | raw == "False"){
               validation <- F
                 } else{
                     validation <- T
                       }
           rm(raw)  } else{
#  non-interactive
cat("a string please: ");
a <- readLines("stdin",n=1);
cat("You entered")
 str(a);
cat( "\n" )}

Leave a Comment