From simon.urbanek at r-project.org  Tue Dec  7 19:09:02 2010
From: simon.urbanek at r-project.org (Simon Urbanek)
Date: Tue, 7 Dec 2010 13:09:02 -0500
Subject: [Rd] Wait for user input with readline()
In-Reply-To: <20101207171921.GA21470@cs.cas.cz>
References: <AANLkTikAG_8ynt2+SP=b5WYJ2u2w5iwqit=0R_1FDsJr@mail.gmail.com>
	<1291652739318-3074781.post@n4.nabble.com>
	<20101207171921.GA21470@cs.cas.cz>
Message-ID: <5C3B1203-2810-4CBE-9501-A3F2A36C18C3@r-project.org>


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:
input=file("stdin")
print(readLines(input,1))
which works both in interactive and non-interactive setting and expects input in both cases (if you use Rscript or R -e 'source("...")' ).

Cheers,
Simon



[Rd] Wait for user input with readline()
Simon Urbanek