đ 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
đ¯ 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
| Function | Purpose |
|---|---|
| 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
đ 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
đ Common File Formats
| Format | Extension | Typical Use |
|---|---|---|
| CSV | .csv | Data exchange and spreadsheets. |
| Text | .txt | Plain text information. |
| R Data | .RData | Saving R objects. |
| Table | .txt or .dat | Tabular datasets. |
â ī¸ Common Mistakes
| Mistake | Explanation | Solution |
|---|---|---|
| Incorrect file path | R cannot locate the file. | Verify the working directory or use the full file path. |
| Using the wrong separator | Imported data may appear in a single column. | Specify the correct sep value. |
| Overwriting existing files | Important data may be lost. | Use a different output file name or create backups. |
| Ignoring missing values | Analysis 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
đ 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.