Waiting for user input in R from terminal

I managed 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 this from the terminal using the code below, it simply moves on to the next line without user input. How can I overcome this?

word <- readline(prompt="Enter a word: ")
print(word);
+4
source share
2 answers

The user input is the line after readline. Try the following:

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

Update

Waiting for input in the console:

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

or

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

Add this line to the top of your program:

args<-commandArgs(TRUE)

and then enter the input with the rscript line as:

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

All Articles