How to Read User Input Data in R

If you are creating a console or terminal-based application, you need to figure out how to read the input data from the user. Let’s see how to read user input data.

Read User Input Data in R

To read the user input in R, use the readline() function. The readline() function reads a line from the terminal. You can use it with an interactive shell. Otherwise, it won’t work.

The prompt string will be truncated to a maximum allowed length, normally 256 chars.

Syntax

readline(prompt = "")

Arguments

prompt: It is the string printed when prompting the user for input. Should usually end with space ” “.

Return Value

The readline() function returns a character vector of length one. Both leading and trailing spaces and tabs are stripped from the final result.

Example

Let’s take create a program where the user will be asked for two inputs, and after reading the input, it will multiply it and returns the result.

Open the RStudio and write the following code.

multiplyUserInput <- function(x, y) {

 x <- as.numeric(unlist(strsplit(x, ",")))
 y <- as.numeric(unlist(strsplit(y, ",")))

 op <- x * y

 return(list(op))
}

a <- readline("Type the value of a: ")
b <- readline("Type the value of b: ")

multiplyUserInput(a, b)

Output

Type the value of a: 19
Type the value of b: 21

[1] 399

If you run the above code in the interactive R shell, you will see the above output.

By default, if you are reading from the user input, it will be a string. The strsplit() method returns the list, where each list element resembles the item of input that has been split.

The unlist() function is used to convert a list to vector in R. The unlist() function takes the list as an argument and returns the Vector. It flattens the list.

To convert string to the numeric value in R, use the as.numeric() function. We used the as.numeric() function and unlist() function.

If you run the above code in non-interactive use, the result is as if the response was RETURN and the value is “”.

That is it for the reading user input in R language.

Leave a Comment