2

How to invoke an R script like the following

scan()

in Windows? When using either R or Rscript, nothing is read. With Rscript or littler (both on Linux) the script works as expected.

# Doesn't work because stdin is already redirected
R --no-save < test.R

# Works on Linux, doesn't on Windows
Rscript test.R

# Works on Linux, doesn't exist in Windows
r test.R

Is there any way at all to achieve this without changing the R code?

Perhaps related: Why is there no --interactive switch in Windows?

krlmlr
  • 25,056
  • 14
  • 120
  • 217
  • Please present us with a reproducible example. – Paul Hiemstra Nov 07 '12 at 13:36
  • This is discussed in an [R devel post](http://r.789695.n4.nabble.com/Wait-for-user-input-with-readline-td3054517.html). – nograpes Nov 07 '12 at 15:15
  • 1
    Never tried on Windows (so I don't post it as an answer) but a script containing `scan(file("stdin"))` will work on a Mac. – plannapus Nov 09 '12 at 14:23
  • 1
    @plannapus It does work on Windows. I'll let you post the answer if you want to get the points. You have to modify it slightly so that it takes `character` and you have to hit `Ctrl+Z` to end scanning: `input<-scan(file("stdin"), what = character()) ` – nograpes Nov 09 '12 at 14:55

1 Answers1

5

So as we discussed in the comments and with confirmation of @nograpes, you can use the following:

scan(file("stdin"), what=character())

in a script instead of scan() to read interactively from standard input when the script is executed in the command-line interface.
You then need to hit Ctrl + Z to end scanning under Windows (Ctrl + D on a Mac).

plannapus
  • 18,529
  • 4
  • 72
  • 94
  • Why is the behavior different in Windows and Unix? – krlmlr Nov 12 '12 at 17:07
  • I'm working on a Mac (so Unix) and I have to supply `file("stdin")` as well. I have no competence in Linux, so can't really help on that one I guess. – plannapus Nov 15 '12 at 07:49