waiting for user input in R from terminal

2019-04-29 18:07发布

问题:

I was able to wait for user input in R when running my script as Rscipt myscript.R from the command line as follows and reading the input from stdin.

cat("Enter word : ")
word <- readLines(file("stdin"),1)
print(word);

However, when I try to do it from the terminal using the below code, it just goes to the next line without taking user input. How do I overcome this?

word <- readline(prompt="Enter a word: ")
print(word);

回答1:

The "user" input is the line after readline. Try this:

word <- readline(prompt="Enter a word: ")
Hello world!
print(word)

Update

To wait for input in the console:

word <- readline(prompt="Enter a word: "); print(word)

or

{
  word <- readline(prompt="Enter a word: ")
  print(word)
}


回答2:

Add this line to top of your program:

args<-commandArgs(TRUE)

and then give input with the Rscript line as:

Rscript filename.r args[1] args[2] ...


标签: r rstudio