Make readline wait for input in R

I am trying to have my code ask me the meaning of TRUE or FALSE before continuing.

Currently, it works fine if I run it one line at a time, however, when I run all the code at once in RStudio, it just continues without waiting for user input and writing the value "" 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 need an answer that works no matter how I run it - RScript , source in RStudio or run it (i.e. select the code and press run or ctrl-enter).

+5
source share
2 answers

If you want to do this interactively, you already have answers, but not for use with Rscript. To do this, you need to send messages to the console using cat :

If this test file is named "prompt.r" and is located in the directory where you are working in the 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 need a universal script, then it will run your script in interactive conditions and my script for non-interactive:

 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" )} 
+12
source

Do you execute code by highlighting lines and clicking the "Run" button? If so, this may be your problem, because R is in turn entering your code in the terminal.

Instead, write a script (or comment out the parts that you are not testing) and click the source button. R then waits for the user's response instead of entering a line after readline () in readline ().

I had the same problem as you, which prompted me to look for an answer. But then I tried this other code execution method and it worked.

+8
source

Source: https://habr.com/ru/post/1207612/


All Articles