I am trying to use
var <- as.numeric(readline(prompt="Enter a number: "))
and later use this in a calculation.
It works fine when running in RStudio but I need to be able to pass this input from the command line in Windows 10 I am using a batch file with a single line
Rscript.exe "C:\My Files\R_scripts\my_script.R"
When it gets to the user input part it freezes and it doesn't provide expected output.
CodePudding user response:
From the documentation of readline()
:
This can only be used in an interactive session. [...] In non-interactive use the result is as if the response was RETURN and the value is "".
For non-interactive use - when calling R from the command line - I think you've got two options:
- Use
readLines(con = "stdin", n = 1)
to read user input from the terminal. - Use
commandArgs(trailingOnly = TRUE)
to supply the input as an argument from the command line when calling the script instead.
Under is more information.
1. Using readLines()
readLines()
looks very similar to readline()
which you're using, but is meant to read files line by line. If we instead of a file points it to the standard input (con = "stdin"
) it will read user input from the terminal. We set n = 1
so that it stops reading from the command line when you press Enter (that is, it only read one line).
Example
Use readLines()
in a R-script:
# some-r-file.R
# This is our prompt, since readLines doesn't provide one
cat("Please write something: ")
args <- readLines(con = "stdin", n = 1)
writeLines(args[[1]], "output.txt")
Call the script:
Rscript.exe "some-r-file.R"
It will now ask you for your input. Here is a screen capture from PowerShell, where I supplied "Any text!".
Then the output.txt will contain:
Any text!
2. UsingcommandArgs()
When calling an Rscript.exe
from the terminal, you can add extra arguments. With commandArgs()
you can capture these arguments and use them in your code.
Example:
Use commandArgs()
in a R-script:
# some-r-file.R
args <- commandArgs(trailingOnly = TRUE)
writeLines(args[[1]], "output.txt")
Call the script:
Rscript.exe "some-r-file.R" "Any text!"
Then the output.txt will contain:
Any text!