How to Enter from Keyboard in Non-Interactive Mode in R

It happens often that we need to enter some parameters from keyboard when we’re running a R script. An example is that we need to choose from a few options provided by R program. You may already have the idea how to figure this out: readline() or scan(). It would work well if you’re running R in interactive mode.

But if you’re running R script in non-interactive mode, surprisingly, it will fail. For example, you run a R scirpt by simply clicking it on Windows platform (after setting “open with” as “R for Windows front-end”), or you use Rscript command to call a R script in command line on Unix platform. If any line contains readline() or scan(), the program will not wait for you. It will directly pass value '' to R, which is not what you expected. The help document of readline() also emphasized that “This can only be used in an interactive session”.

What can we do?

One solution is to force the ‘file’ argument in scan() function to be ‘stdin’, just like below

cat("Enter something:\n")
result <- scan("stdin", character(), n=1)

#### Code Example

Save this script and run it by clicking on Windows platform, or by ‘Rscript’ command on Unix platform.

# Print the files in current folder and corresponding numbers
file_list=dir()
for(i in 1:length(file_list)){
cat(i, ":", file_list[i], "\n")
}

# user choose the file to process further.
cat("\nEnter the NUMBER to choose file: ")
choice <- as.numeric(scan("stdin", character(), n=1))
print(file_list[choice])

Another wrong code example is also given. It may look well, cand can work well in interactive mode, but you can give a try to run it in non-interactive mode.

# Print the files in current folder and corresponding numbers
file_list=dir()
for(i in 1:length(file_list)){
cat(i, ":", file_list[i], "\n")
}

# user choose the file to process further.
cat("\nEnter the NUMBER to choose file: ")
choice <- as.numeric(scan())
print(file_list[choice])