readline()
readline(prompt = NULL) readline() reads a line of text from the console (interactive session) or from a connection. It pauses execution until the user enters text and presses Enter. This function is essential for creating interactive R scripts and user prompts.
Syntax
readline(prompt = NULL)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
prompt | character | NULL | A character string to display as the prompt before reading input |
The prompt argument is optional — if you omit it, readline() waits silently with no on-screen cue, which can confuse users who do not realize the session is waiting. Including a clear prompt string is a small courtesy that makes interactive scripts far more usable. The examples below start with simple prompts and build toward multi-field data entry.
Examples
Basic usage
# Interactive prompt for user name
name <- readline("What is your name? ")
# User types: Alice
# Output: "Alice"
# Using the input
paste("Hello,", name)
# Output: "Hello, Alice"
readline() always returns a character string — even when the user types a number. If your script needs numeric input, you must convert the result explicitly with as.numeric() or as.integer(). This is a frequent source of bugs when the conversion silently produces NA for non-numeric entries, so wrapping the conversion in a validation check is a good habit to develop early.
Getting numeric input
# Reading and converting to numeric
age <- readline("Enter your age: ")
age <- as.numeric(age)
# User types: 25
# Output: 25
Single-field prompts cover the simplest use case, but real data-entry workflows collect several pieces of information in sequence. You can chain multiple readline() calls to gather name, email, department, or any set of fields the user needs to supply, then assemble the responses into a data frame for further processing or storage.
Multiple prompts in a script
# Creating an interactive data entry workflow
cat("=== New Entry ===\n")
name <- readline("Name: ")
email <- readline("Email: ")
department <- readline("Department: ")
data <- data.frame(
name = name,
email = email,
department = department
)
print(data)
Collecting raw input is only half the story — users make typos, enter out-of-range values, or skip required fields. The real power of readline() emerges when you pair it with validation logic that checks the response and re-prompts until the input meets your criteria. This loop-until-valid pattern turns a simple prompt into a reliable data-capture mechanism.
Common patterns
Input validation: Combine readline() with while loops to validate user input.
get_valid_choice <- function() {
choice <- readline("Enter 1, 2, or 3: ")
while (!choice %in% c("1", "2", "3")) {
choice <- readline("Invalid. Enter 1, 2, or 3: ")
}
return(choice)
}
Validating against a fixed set of allowed values covers numeric menus and enumerated choices, but the most common interactive pattern in scripts is the binary yes/no confirmation. Rather than requiring the full word, a common convention is to check only the first character — tolower(substr(confirm, 1, 1)) == "y" — so that “y”, “Y”, “yes”, and “Yes” all count as affirmative without extra work.
Interactive yes/no prompts:
confirm <- readline("Continue? (y/n): ")
if (tolower(substr(confirm, 1, 1)) == "y") {
print("Proceeding...")
} else {
print("Cancelled.")
}
readline() in practice
readline() reads a single line of input from the user at an interactive R session. It displays the prompt argument and waits until the user presses Enter. The returned value is always a character string, if the user types 42, the result is "42", not 42L. Convert with as.numeric() or as.integer() if a numeric value is needed.
readline() only works in interactive sessions. In non-interactive contexts (batch scripts, RMarkdown documents, Shiny apps, automated pipelines), readline() returns "" immediately without waiting for input. Use interactive() to check before calling: if (interactive()) readline("Enter value: ") else default_value.
For reading input in Shiny applications, use textInput() and numericInput() widgets instead. For reading from files or standard input in batch processing, use readLines(stdin(), n=1) or file connections. readline() is specifically for one-off interactive prompts in console scripts.
scan() is the more powerful alternative for reading multiple values: scan(n=3) reads three space-separated values from the console. readLines() reads multiple lines. For structured data entry, these are more appropriate than calling readline() in a loop.
readline() blocks execution and waits for the user to type a line. It only works in interactive sessions, in a script run non-interactively, it returns an empty string immediately. For reading input in scripts, use readLines("stdin", n = 1) or scan(file = "stdin", what = "", n = 1). In Shiny apps, use textInput() instead. readline() always returns a character string, so numeric input requires as.numeric().
See also
- cat()
- print()
- rep()The
readline()function is primarily for interactive use; for scripts that need prompting,menu()provides a numbered option list.readline()always returns a character string, so numeric input needsas.numeric(readline()). For validation loops:repeat { x <- readline("Enter age: "); age <- suppressWarnings(as.numeric(x)); if (!is.na(age) && age > 0) break; cat("Please enter a positive number\n") }. In non-interactive scripts,readline()returns an empty string without blocking — test interactivity withinteractive()before calling. Therstudioapi::showPrompt()function provides a GUI dialog in RStudio sessions.