[Rd] Wait for user input with readline()

Simon Urbanek simon.urbanek at r-project.org
Tue Dec 7 19:09:02 CET 2010

On Dec 7, 2010, at 12:19 PM, Petr Savicky wrote:

> On Mon, Dec 06, 2010 at 08:25:39AM -0800, Alexandre wrote:
>> Hi,
>> I have a similar problem as the one of Nate. The point is that I want to
>> design an interactive script that need the value of two variables (x and y).
>> So my script as designed for the moment is :
>> x <- as.numeric (readline(prompt="What is the value of x? "))
>> y <- as.numeric (readline(prompt="What is the value of y? "))
>> x
>> y 
>> But the problem is that if I run this script, values returned for x and y
>> will be "NA" like you can see below :
> How do you call your code? Function readline() does not wait for
> user input in a non-interactive session, for example R CMD BATCH
> or Rscript.
> Another situation, when readline() does not wait is, when you copy
> a block of code and paste it to a running session, even if it is
> interactive. If readline() is not the last line of the code, then
> the next line of code is used instead of the user input.

You can't tell R code and input apart in cases like
R < myScript.R
but you can if you use source() or Rscript -- and you can treat them differently.

I assume what Alexandre wants is something like:
which works both in interactive and non-interactive setting and expects input in both cases (if you use Rscript or R -e 'source("...")' ).


More information about the R-devel mailing list