π R File Operations: Your Digital Filing Cabinet
Imagine your computer is a huge library. R is your super-smart librarian who can read books, write new ones, organize shelves, and remember exactly where everything goes!
π― The Big Picture
Think of file operations like running a post office:
- π€ Output = Sending letters out (showing messages)
- π₯ Input = Receiving letters (reading data)
- π Files = The actual letters and packages
- ποΈ Directories = The mailroom shelves
Letβs learn how R becomes your personal mail carrier!
π€ Console Output Functions
What Are They?
Output functions are like a megaphone for R. They let R βspeakβ to you by showing messages on the screen.
The Main Tools
print() - The Basic Announcer
print("Hello, World!")
# Output: [1] "Hello, World!"
x <- 42
print(x)
# Output: [1] 42
cat() - The Cleaner Speaker
cat("My name is R!\n")
# Output: My name is R!
cat("Score:", 100, "\n")
# Output: Score: 100
π‘ Key Difference:
print()shows quotes and[1].cat()gives clean, simple output!
message() - For Important Notes
message("Loading data...")
# Shows in different color (diagnostic)
warning() - Yellow Flag Alert
warning("File might be old!")
# Shows a warning message
π₯ Console Input Functions
What Are They?
Input functions are like asking a question and waiting for an answer. R pauses and listens!
readline() - Ask and Listen
name <- readline("What is your name? ")
# User types: Alice
# name now contains "Alice"
cat("Hello,", name, "!\n")
# Output: Hello, Alice !
scan() - Read Multiple Values
numbers <- scan(n = 3)
# User types: 10 20 30
# numbers = c(10, 20, 30)
graph TD A["R asks question"] --> B["User types answer"] B --> C["R stores the answer"] C --> D["R uses the answer"]
π Reading CSV and Table Files
The Magic of CSV Files
CSV = Comma Separated Values
Think of it like a spreadsheet saved as simple text:
name,age,score
Alice,10,95
Bob,12,88
read.csv() - Your CSV Reader
# Read a CSV file
students <- read.csv("students.csv")
# See what's inside
head(students)
read.table() - More Flexible Reader
# Read any table file
data <- read.table(
"data.txt",
header = TRUE,
sep = "\t" # Tab-separated
)
Common Options
| Option | What It Does |
|---|---|
header = TRUE |
First row has column names |
sep = "," |
Fields split by commas |
stringsAsFactors = FALSE |
Keep text as text |
na.strings = "NA" |
What counts as missing |
πΎ Writing CSV and Table Files
Saving Your Work
Just like saving a game, you need to save your data!
write.csv() - Save as CSV
# Create some data
students <- data.frame(
name = c("Alice", "Bob"),
score = c(95, 88)
)
# Save it!
write.csv(students, "my_data.csv")
write.table() - More Control
write.table(
students,
"my_data.txt",
sep = "\t",
row.names = FALSE
)
β οΈ Pro Tip: Use
row.names = FALSEto avoid an extra mystery column!
graph TD A["Your Data in R"] --> B{Choose Format} B -->|CSV| C["write.csv"] B -->|Custom| D["write.table"] C --> E["file.csv"] D --> F["file.txt"]
π Reading and Writing Text Files
Simple Text - Like Notes!
Sometimes you just want to read or write plain text, like a diary.
readLines() - Read Text File
# Read all lines from a file
poem <- readLines("poem.txt")
# poem is a vector of lines
print(poem[1]) # First line
writeLines() - Write Text File
# Create some lines
my_lines <- c(
"Line one",
"Line two",
"The end!"
)
# Save to file
writeLines(my_lines, "note.txt")
readr Package - Modern Way
library(readr)
# Fast reading
text <- read_file("story.txt")
# Fast writing
write_file("Hello!", "greeting.txt")
πΌ R Object Persistence
What Is Persistence?
Persistence means saving R objects so they survive when you close R. Like freezing food to eat later!
save() - Freeze Objects
x <- 100
y <- c(1, 2, 3)
# Save these objects
save(x, y, file = "my_stuff.RData")
load() - Unfreeze Objects
# Later, bring them back!
load("my_stuff.RData")
print(x) # 100 is back!
saveRDS() / readRDS() - Single Object
# Save ONE object
big_result <- lm(mpg ~ wt, data = mtcars)
saveRDS(big_result, "model.rds")
# Load it back with any name
my_model <- readRDS("model.rds")
graph TD A["R Objects in Memory"] --> B{How Many?} B -->|Multiple| C["save / load"] B -->|One| D["saveRDS / readRDS"] C --> E[".RData file"] D --> F[".rds file"]
π‘ Best Practice: Use
.rdsfor single objects,.RDatafor multiple!
ποΈ Working Directory Management
What Is Working Directory?
The working directory is Rβs βhome baseβ - the folder where R looks for files by default.
Think of it like: Where am I standing in the library?
getwd() - Where Am I?
getwd()
# "/Users/alice/projects"
setwd() - Move to New Folder
setwd("/Users/alice/data")
# Now R looks here first!
Best Practice: Use Projects!
Instead of setwd(), use RStudio Projects. They automatically set the right folder!
graph TD A["Open R"] --> B["getwd - Check location"] B --> C{Right folder?} C -->|No| D["setwd - Change location"] C -->|Yes| E["Start working!"] D --> E
π File System Operations
R as File Manager
R can do everything your file explorer does!
Check If File Exists
file.exists("data.csv")
# TRUE or FALSE
List Files in Folder
# All files
list.files()
# Only CSV files
list.files(pattern = "\\.csvquot;)
Create Folders
dir.create("new_folder")
# Create nested folders
dir.create("a/b/c", recursive = TRUE)
Copy, Move, Delete
# Copy a file
file.copy("old.txt", "new.txt")
# Rename/Move
file.rename("old.txt", "moved.txt")
# Delete (careful!)
file.remove("temp.txt")
Get File Info
file.info("data.csv")
# Shows size, modified date, etc.
Path Helpers
# Combine paths safely
file.path("folder", "file.csv")
# "folder/file.csv"
# Get just the filename
basename("/path/to/file.csv")
# "file.csv"
# Get just the folder
dirname("/path/to/file.csv")
# "/path/to"
π Quick Summary
| Task | Function |
|---|---|
| Show message | print(), cat() |
| Ask user | readline() |
| Read CSV | read.csv() |
| Write CSV | write.csv() |
| Read text | readLines() |
| Write text | writeLines() |
| Save objects | save(), saveRDS() |
| Load objects | load(), readRDS() |
| Current folder | getwd() |
| Change folder | setwd() |
| File exists? | file.exists() |
| List files | list.files() |
| Create folder | dir.create() |
| Delete file | file.remove() |
π You Did It!
You now know how to:
- β Talk to users with output functions
- β Listen to users with input functions
- β Read and write CSV files
- β Handle text files like a pro
- β Save R objects for later
- β Navigate folders like a file explorer
- β Manage files programmatically
R is now your personal file assistant! πβ¨
