Have a fully working R-script. When executing it from Rscript it doesn't stop to accept user input however. The user input is some readline statements. The cat statements prompting for input works as intended. Have I missed something? I execute 'Rscript scriptfile.R' from terminal on macOS.
Asked
Active
Viewed 1,598 times
3 Answers
3
You can create a function typeline() to read an input line and then use the result for your next commands. It will wait for your input text either you run your code in Rstudio or in terminal:
typeline <- function(msg="Enter text: ") {
if (interactive() ) {
txt <- readline(msg)
} else {
cat(msg);
txt <- readLines("stdin",n=1);
}
return(txt)
}
txt=typeline("your message: ")
print(txt)

rafaoc
- 586
- 7
- 21
1
Managed to get it to work by changing readline to readLines as mentioned in the post suggested by meenaparam. The downside with this method is that ithe script only works in batch mode, running it in Rstudio makes it hang. Would be good to know a general way to capture keyboard input i.e that works both in interactive and batch mode.

wabe
- 93
- 5
1
Use this
cat("What's your name? ")
name <- readLines(file("stdin"),1)
cat("What's your age? ")
age <- readLines(file("stdin"),1)
print(name)
print(age)

Deepak
- 21
- 2