Hack-R Hack-R - 3 months ago 60
R Question

Make readline wait for input in R

I'm trying to make my code ask me for a "TRUE" or "FALSE" value before proceeding.

It currently works fine if I run it one line at a time, however when I run all the code at once in RStudio it simply proceeds without waiting for user input and records a value of "" for my parameter.

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


if (raw == "F" | raw == "FALSE" | raw == "False"){
validation <- F
} else{
validation <- T
}
rm(raw)


Ideally, I would like an answer that works regardless of how I run it --
RScript
,
source
within RStudio, or running it (i.e. selecting the code and pressing
run
or ctrl-enter).

42- 42-
Answer

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" )}