I was trying to test using stdin and stdout in RStudio, and used the command
library(readr)
lines -> read_lines(stdin())
to capture intput, but when I was done, nothing ended the input no matter what I tried (various Unix Ctrl-* keystrokes and the "Stop" icon). I was only able to get it to stop by terminating my R session.
Thanks for the clarifying question, @technocrat : Yes, I was trying to figure out the basics of interacting with the user through standard input, which I thought was supplied by the user through the console.
I thought that might be the case. I asked my assistant to look into it and this is what was found:
In the R programming language, there are two primary functions available to prompt users for input in interactive sessions: readline() and scan().
readline(): This function is used to take input from the user (terminal) in an interactive session. It returns a single element character vector. If you want to input numbers, you need to perform appropriate conversions. The prompt argument allows you to display a message for the user
Example:
my.name <- readline(prompt="Enter name: ")
my.age <- readline(prompt="Enter age: ")
# Convert character into integer
my.age <- as.integer(my.age)
print(paste("Hi,", my.name, "next year you will be", my.age+1, "years old."))
scan(): This function takes input from the console and can read data in the form of a vector or list. It can also be used to read input from a file. To terminate the input process, press the Enter key twice on the console.
Example:
x = scan()
print(x)
You can also use scan() with specific data types by specifying the what parameter
d = scan(what = double())
s = scan(what = " ")
ch = scan(what = character())
Remember that the input taken by readline() is in string format, so you may need to convert the input to the desired data type using functions like as.integer(), as.numeric(), or as.character()
Thanks, @technocrat; this is good for reading single line of input, but I was trying to figure out how to enter and terminate multi-line input (although I forgot to mention that when you asked for clarification). I'll modify the topic title so it's clearer. Do you have an idea why read_lines() can't be used?