0
0
R-programmingHow-ToBeginner · 3 min read

How to Take Input in R: Simple Guide with Examples

In R, you can take input from the user using the readline() function, which reads a line of text from the console. To convert this input to a number, use functions like as.numeric() or as.integer().
📐

Syntax

The basic syntax to take input in R is using the readline(prompt = "") function. The prompt is a message shown to the user before input.

Since readline() returns a string, you often convert it to a number using as.numeric() or as.integer().

r
input_value <- readline(prompt = "Enter something: ")
# Convert to number if needed
numeric_value <- as.numeric(input_value)
💻

Example

This example asks the user to enter their age, reads it as text, converts it to a number, and then prints a message with the age.

r
age_input <- readline(prompt = "Enter your age: ")
age <- as.numeric(age_input)
if (!is.na(age)) {
  cat("You are", age, "years old.\n")
} else {
  cat("Please enter a valid number.\n")
}
Output
Enter your age: 25 You are 25 years old.
⚠️

Common Pitfalls

  • Forgetting that readline() returns a string, so numeric operations need conversion.
  • Not handling invalid input that cannot convert to numbers, which results in NA.
  • Using scan() without proper parameters can confuse beginners.
r
## Wrong way: Using input directly as number
age <- readline(prompt = "Enter age: ")
cat(age + 5)  # This causes an error

## Right way: Convert input to numeric first
age_input <- readline(prompt = "Enter age: ")
age <- as.numeric(age_input)
if (!is.na(age)) {
  cat(age + 5, "is your age plus 5.\n")
} else {
  cat("Invalid number entered.\n")
}
📊

Quick Reference

Here is a quick summary of how to take input in R:

  • readline(prompt = "Message"): Reads input as string.
  • as.numeric(): Converts string to number (decimal).
  • as.integer(): Converts string to integer.
  • Always check for NA after conversion to handle invalid input.

Key Takeaways

Use readline() to get user input as a string in R.
Convert input to numeric types with as.numeric() or as.integer() before calculations.
Always check for NA to handle invalid numeric input gracefully.
Provide clear prompts to guide the user when asking for input.