16

I am trying to write an interactive R script. For example:

try.R:

print("Entr some numbers. >",quote=F)
a = scan(what=double(0))
print a
q()

Now, if I run it on the command line as

$ R --no-save < try.R

It tries to get the stdin from try.R, giving the following error:

> print("Entr some numbers. >",quote=F)
[1] Entr some numbers. >
> a = scan(what=double(0))
1: print a
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  : 
  scan() expected 'a real', got 'print'
Execution halted

I tried a few other methods but they all give errors. For example:

$ R CMD BATCH try.R 
$ Rscript try.R 

So how do I write an R script that works from the *nix shell command line, and can take in interactive input from the user?

user229044
  • 232,980
  • 40
  • 330
  • 338
highBandWidth
  • 16,751
  • 20
  • 84
  • 131

3 Answers3

21

Try this:

cat("What's your name? ")
x <- readLines(file("stdin"),1)
print(x)

Hopefully some variant of that works for you.

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • 1
    My bad, sorry. I happened to have used `readLines()` without a file argument, defaulting to stdin, at the same time -- see r-help as of this morning. – Dirk Eddelbuettel Oct 14 '10 at 17:38
  • @Dirk, apparently `file("stdin")` and `stdin()` can refer to different things in different situations. See `?file` and `?stdin`. – Joshua Ulrich Oct 14 '10 at 17:46
  • 1
    Dirk, this works fine in my CentOS machine but doesn't work in my Windows R. Is there a way to make it work in Windows as well? – Ravi Jun 04 '14 at 12:06
4

What worked for me on Windows with RStudio 0.98.945 and R version 3.1.1 was:

    cat("What's your name? ")
    x <- readLines(con=stdin(),1)
    print(x)
Paulo S. Abreu
  • 183
  • 1
  • 3
  • 8
  • `stdin()` behaves differently when called from a GUI or from inside a command-line script (see `?stdin`). This question is about the latter. – Christian David May 30 '18 at 16:16
0

The answer by @Joshua Ulrich is fine for Linux, but hangs under macOS and needs to be terminated using Ctrl-D.

This is a work-around for both Linux and macOS:

#!/usr/bin/env Rscript

print(system("read -p 'Prompt: ' input; echo $input", intern = TRUE))
Christian David
  • 455
  • 5
  • 12
  • I can confirm that `readLines` works as expected on macOS. The issue is simply that `cat` without a trailing newline doesn’t reliably flush and thus there’s no prompt — manually flushing helps (but in my testing even this isn’t actually necessary in non-interactive scripts). It’s definitely *not* necessary (and not portable!) to call external tools. – Konrad Rudolph May 20 '19 at 10:03