Input and Output in R

📘 Introduction

Input and Output (I/O) are essential operations in every programming language. Input refers to receiving data from users, files, or other sources, while output refers to displaying or saving processed information. R provides several built-in functions for reading user input, displaying results, and working with files.

Information

Input and output operations enable R programs to interact with users, making applications dynamic, flexible, and useful for real-world tasks.

đŸŽ¯ Why Learn Input and Output?

  • Accept information from users.
  • Display processed results.
  • Read data from files.
  • Write results to files.
  • Create interactive R applications.

📚 Types of Input and Output

Input and Output
Console Input
Console Output
File Input
File Output

âŒ¨ī¸ Console Input

The readline() function accepts input from the user through the console. Since the returned value is a character string, numeric input should be converted when necessary.

Reading User Input

name <- readline(prompt = "Enter your name: ")

print(paste("Hello", name))

đŸ”ĸ Reading Numeric Input

Use as.numeric() to convert user input into a numeric value.

Numeric Input

age <- as.numeric(
  readline(prompt = "Enter your age: ")
)

print(age)

đŸ–Ĩ Console Output

R provides several functions for displaying information in the console.

FunctionDescription
print()Displays objects in the console.
cat()Displays formatted text without quotation marks.
message()Displays informational messages.
warning()Displays warning messages.

📝 Using print()

print() Function

name <- "Alice"

print(name)
print(100)
print(c(10,20,30))

Output

Console Output

[1] "Alice"
[1] 100
[1] 10 20 30

đŸ“ĸ Using cat()

The cat() function is commonly used for formatted output and does not display quotation marks.

cat() Function

name <- "Alice"

cat("Welcome", name)
cat("\nAge:", 22)

Output

Console Output

Welcome Alice
Age: 22

đŸ’Ŧ Using message()

Displaying Messages

message("Data loaded successfully.")

Output

Console Output

Data loaded successfully.

âš ī¸ Using warning()

Displaying Warnings

warning("Missing values detected.")

📂 Reading Data from a File

The read.csv() function imports data stored in CSV (Comma-Separated Values) files.

Reading a CSV File

students <- read.csv("students.csv")

head(students)

💾 Writing Data to a File

The write.csv() function saves data frames as CSV files.

Writing a CSV File

students <- data.frame(
  Name = c("Alice", "Bob"),
  Marks = c(85, 90)
)

write.csv(
  students,
  "students.csv",
  row.names = FALSE
)

📄 Reading Text Files

Use the readLines() function to read plain text files line by line.

Reading a Text File

text <- readLines("notes.txt")

print(text)

📝 Writing Text Files

The writeLines() function writes character data to a text file.

Writing a Text File

content <- c(
  "Welcome to R",
  "Learning Input and Output"
)

writeLines(
  content,
  "notes.txt"
)

📊 Formatted Output Using paste()

The paste() function combines values into readable messages before displaying them.

Formatted Output

name <- "Sophia"
marks <- 92

print(
  paste(
    "Student:",
    name,
    "| Marks:",
    marks
  )
)

Output

Console Output

[1] "Student: Sophia | Marks: 92"

🌍 Real-World Example

The following program accepts a student's name and marks from the user and displays the entered information.

Student Information

name <- readline(
  prompt = "Enter student name: "
)

marks <- as.numeric(
  readline(
    prompt = "Enter marks: "
  )
)

cat(
  "Student:",
  name,
  "\nMarks:",
  marks
)

🔄 Input and Output Workflow

Receive Input
Process Data
Generate Results
Display Output
Save to File (Optional)

📋 Console I/O vs File I/O

FeatureConsole I/OFile I/O
SourceUser keyboard.Files on storage.
Output DestinationConsole screen.CSV, text, or other files.
Typical UseInteractive programs.Persistent data storage.
Functionsreadline(), print(), cat()read.csv(), write.csv(), readLines(), writeLines()

âš ī¸ Common Mistakes

MistakeExplanationSolution
Forgetting to convert numeric inputreadline() always returns a character string.Use as.numeric() or as.integer().
Using print() instead of cat() for formatted textprint() includes quotation marks and object formatting.Use cat() for cleaner output.
Providing an incorrect file pathFile reading or writing fails.Verify the file name and directory.
Overwriting important filesExisting data may be replaced.Choose output file names carefully.

💡 Best Practices

  • Validate user input before processing it.
  • Use descriptive prompts when requesting input.
  • Convert input values to the appropriate data type.
  • Use cat() for readable console messages.
  • Handle file paths carefully to avoid read or write errors.

Best Practice

Effective input and output operations make R programs interactive and user-friendly. Always validate inputs, format outputs clearly, and handle files carefully to build reliable applications.

📝 Summary

Input and output operations allow R programs to communicate with users and external files. You learned how to accept user input using readline(), display information using print(), cat(), message(), and warning(), and read from or write to CSV and text files using functions such as read.csv(), write.csv(), readLines(), and writeLines(). Mastering input and output is essential for creating interactive programs and managing data effectively in R.

>>"Input brings data into your program, and output transforms that data into meaningful information for users."