Reading and Writing Files in R

📘 Introduction

Reading and writing files allows R programs to import data from external sources and save processed results for future use. File operations are essential in data analysis, reporting, scientific research, and business applications because they enable programs to work with datasets stored outside the R environment.

Information

R supports many file formats, including CSV, text, Excel (with packages), R data files, and more. The most commonly used formats are CSV and plain text files.

đŸŽ¯ Why Read and Write Files?

  • Import datasets for analysis.
  • Save processed results.
  • Exchange data with other applications.
  • Create reports and backups.
  • Store information permanently.

📚 Common File Functions

FunctionPurpose
read.csv()Reads data from a CSV file.
write.csv()Writes data to a CSV file.
read.table()Reads tabular data.
write.table()Writes tabular data.
readLines()Reads a text file line by line.
writeLines()Writes text to a file.
save()Saves R objects.
load()Loads saved R objects.

📂 Reading a CSV File

The read.csv() function imports comma-separated values (CSV) into a data frame.

Reading a CSV File

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

print(students)

💾 Writing a CSV File

The write.csv() function exports a data frame to a CSV file.

Writing a CSV File

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

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

📄 Reading a Text File

The readLines() function reads a text file one line at a time.

Reading a Text File

notes <- readLines("notes.txt")

print(notes)

📝 Writing a Text File

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

Writing a Text File

content <- c(
  "Welcome to R",
  "Reading and Writing Files"
)

writeLines(
  content,
  "notes.txt"
)

📊 Reading Tabular Data

The read.table() function imports tabular data with customizable separators.

Reading a Table

employees <- read.table(
  "employees.txt",
  header = TRUE,
  sep = "	"
)

print(employees)

📋 Writing Tabular Data

The write.table() function exports data frames to text files.

Writing a Table

employees <- data.frame(
  ID = c(101, 102),
  Name = c("Alice", "Bob")
)

write.table(
  employees,
  "employees.txt",
  sep = "	",
  row.names = FALSE
)

đŸ’Ŋ Saving R Objects

The save() function stores one or more R objects in an .RData file.

Saving Objects

scores <- c(85, 90, 88)

save(
  scores,
  file = "scores.RData"
)

đŸ“Ĩ Loading R Objects

Use the load() function to restore previously saved R objects.

Loading Objects

load("scores.RData")

print(scores)

📁 Checking the Working Directory

The working directory is the default location where R reads and writes files.

Working Directory

getwd()

📂 Changing the Working Directory

Use setwd() to change the current working directory.

Changing Working Directory

setwd("C:/Users/Student/Documents")

Warning

Use a valid folder path that exists on your computer. File paths differ between operating systems.

📜 Listing Files

The list.files() function displays all files in the current working directory.

Listing Files

list.files()

📊 Viewing Imported Data

After reading a file, use functions such as head(), str(), and summary() to inspect the imported data.

Inspecting Imported Data

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

head(students)

str(students)

summary(students)

🌍 Real-World Example

A company stores monthly sales data in a CSV file. The following example reads the data, calculates the average sales, and saves the updated data to a new CSV file.

Sales Report

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

averageSales <- mean(
  sales$Sales,
  na.rm = TRUE
)

sales$Average <- averageSales

write.csv(
  sales,
  "sales_report.csv",
  row.names = FALSE
)

🔄 File Processing Workflow

Select File
Read Data
Process Information
Analyze or Modify Data
Write Results to a File
Close Process

📋 Common File Formats

FormatExtensionTypical Use
CSV.csvData exchange and spreadsheets.
Text.txtPlain text information.
R Data.RDataSaving R objects.
Table.txt or .datTabular datasets.

âš ī¸ Common Mistakes

MistakeExplanationSolution
Incorrect file pathR cannot locate the file.Verify the working directory or use the full file path.
Using the wrong separatorImported data may appear in a single column.Specify the correct sep value.
Overwriting existing filesImportant data may be lost.Use a different output file name or create backups.
Ignoring missing valuesAnalysis results may be incorrect.Handle missing values after importing the data.

💡 Best Practices

  • Organize data files in dedicated project folders.
  • Check the working directory before reading or writing files.
  • Inspect imported data using head() and str().
  • Use descriptive file names for exported results.
  • Create backups before overwriting important files.

Best Practice

Efficient file handling is the foundation of data analysis in R. Always verify file locations, inspect imported data, and save results with meaningful file names to ensure reliable and reproducible workflows.

📝 Summary

Reading and writing files enables R programs to work with data stored outside the R environment. You learned how to import and export CSV files, read and write text and tabular data, save and load R objects, manage the working directory, list files, and inspect imported datasets. Mastering file operations allows you to efficiently manage datasets, preserve analysis results, and build practical data-driven applications in R.

>>"Files connect your R programs to the real world, allowing data to be stored, shared, analyzed, and preserved."