readline() Function in R
The readline() function in R is used to read a single line of text from the standard input. It is primarily used to interactively obtain information from the user during the execution of a script.
Basic Usage
Reading a Line of Text
# Prompt the user to enter their name name <- readline(prompt="Enter your name: ") print(paste("Hello,", name))
In this example, the function displays a prompt (“Enter your name: “) and waits for the user to input a line of text. Once the user enters the text and presses Enter, the text is stored in the variable name.
Arguments
- prompt: The text to display before the user’s input. This text serves as a prompt and is shown to the user. The default is “”, meaning no prompt message.
Examples
Getting a Password
# Prompt the user to enter a password password <- readline(prompt="Enter your password: ") print("Password entered.")
This code displays a prompt asking the user to enter a password. Note that the password is shown in clear text here; for security reasons, it is better not to display the password after entry.
Reading Numeric Input
# Prompt the user to enter a number number <- as.numeric(readline(prompt="Enter a number: ")) print(paste("The number you entered is:", number))
In this example, readline() reads a line of text which is then converted to a number using as.numeric().
Processing User Input
# Prompt the user to enter multiple values separated by commas values <- strsplit(readline(prompt="Enter values separated by commas: "), ",")[[1]] values <- as.numeric(values) print(values)
This code reads a line of text, splits it into elements separated by commas, and then converts these elements into numbers.
Advanced Usage
Error Handling
To ensure the input is in the expected format (e.g., a number), you can use a validation check and a loop:
repeat { input <- readline(prompt="Enter a number: ") number <- as.numeric(input) if (!is.na(number)) break cat("Invalid input. Please enter a number.\n") } print(paste("The number you entered is:", number))
This code repeatedly prompts the user until they enter a valid numeric value.
Reading Multiple Lines
To read multiple lines, you can use readline() in a loop:
# Read multiple lines until an empty line is entered lines <- c() repeat { line <- readline(prompt="Enter a line (leave empty to finish): ") if (line == "") break lines <- c(lines, line) } print(lines)
Here, the loop continues until the user enters an empty line. Each line entered is added to the lines vector.
Summary
The readline() function is ideal for obtaining interactive input from the user in an R script. It allows you to read a single line of text and is often used for data entry or user interaction. By combining readline() with other functions and techniques, you can handle more complex inputs and perform validations on the entered data.