Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rscript and user prompts

Tags:

r

rscript

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.

like image 303
wabe Avatar asked Aug 14 '26 14:08

wabe


2 Answers

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)
like image 104
rafaoc Avatar answered Aug 17 '26 05:08

rafaoc


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.

like image 24
wabe Avatar answered Aug 17 '26 04:08

wabe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!