[R] readline() and Rterm in Windows

Duncan Murdoch murdoch at stats.uwo.ca
Wed Nov 2 23:08:55 CET 2005


Mikkel Grum wrote:
> Duncan and Prof, thanks for your comments and
> apologies for not being more specific. I'm not getting
> the same results you get from the steps you propose.
> 
> If I write a script foo.R with two lines
> 
> 	id <- readline("Please enter an ID: ")
> 	id
> 
> and then use source("foo.R") (either at the Rterm
> prompt, or in RGui) it is true that get prompted, but
> the second line does not visibly run, i.e. I get
> 
>>source("id.r")
> 
> Please enter an ID: 5
> 
> 
> and if I then type id, I get
> 
>>id
> 
> [1] "id"
> 
> If I cut and paste the two lines in RGui (in one go),
> I get
> 
>>id <- readline("Please enter an ID: ")
> 
> Please enter an ID: id
> 
> 
> What I really want is a batch file on the desktop with
> the following commands:
> 
>    c:\r\R-2.2.0\bin\Rterm.exe --no-save --no-restore
> <script.R> script.out 2>&1
>    c:\texmf\miktex\bin\latex
> \nonstopmode\input{blue.tex}
> 
> 
> and script.R reads something like:
> 
>    id <- readline("Please enter an ID: ")
>    id
>    Sweave("blue.Rnw")
> 
> I said that script.R didn't run, which was an
> incorrect description. It runs without prompting for
> the ID, and gives error messages all through because
> blue.Rnw needs the id.
> 
> This is a very simplified version of what I'm doing,
> but if I use only the first line of the batch file and
> the first two lines of the script and could get that
> to work, I could figure out the rest.

It won't work so simply.  You're redirecting stdin, so user input would 
be taken from there; you're redirecting stdout and stderr, so the prompt 
won't be visible to the user.

You need to open new handles to the console.  The code below will do it 
in Windows; the syntax to specify the console in Unix-alikes will be 
different (but I don't know what it is).

conout <- file('CONOUT$','w')
conin <- file('CONIN$', 'r')
cat('Please enter an ID:', file=conout)
flush(conout)
id <- readLines(conin, 1)
print(id)

Duncan Murdoch




More information about the R-help mailing list