Search code examples
rrstudiouser-inputreadline

Creating a robust readline script in R


My R script below is workable, but not robust because it works only when I run it from the R script file using the shortcut ctrl + alt + r (RStudio), whereas it won't run appropriately using the other shortcut ctrl + a then ctrl + Enter.

How can I make the script more robust to work in any ways?

enterval <- function()  {
   fNumGlobal <<- (readline("Please choose a file to analyze: "))
}

fNumGlobal = -1
enterval()
( fNumGlobal )

The latter case returns a line like this, which is failing to do user-input.

Please choose a file to analyze: ( fNumGlobal )

Solution

  • Putting braces round the code as

    {
    enterval <- function()  {
      fNumGlobal <<- (readline("Please choose a file to analyze: "))
    }
    
    fNumGlobal = -1
    enterval()
    ( fNumGlobal )
    }
    

    Means that none of it will be run until the whole script has been passed into the console window, so there's no possibility for the next line of code to be interpreted as the input to readline.