5. Files - JulTob/R GitHub Wiki
🗺️ Map of File Management
“A wise sailor learns not just to steer the ship, but where to find the map!”
In R, ye often work with external files, like text, CSV, or table files. This chart teaches ye how to read those files into R and store them as usable objects like vectors or data frames.
⸻
🧭 Reading Raw Data with scan()
Use scan() when ye want to read raw numbers or character data into a vector.
> valores <- scan("d:\\datos")
This reads values from a plain text file at that location into a vector called valores.
⚠️ If the file lies in a subdirectory, include the full path:
> valores <- scan("d:\\curso\\datos")
Or use forward slashes like a modern corsair:
> valores <- scan("d:/curso/datos")
Common use cases for scan():
- Simple numeric values
- A list of words or codes
- Input without structure (no columns/rows)
⸻
📊 Reading Tables with read.table()
Use read.table() when the file has rows and columns, like spreadsheets or data logs.
> datos <- read.table("d:\\datos.txt", header = TRUE,
colClasses = c("numeric", "factor"))
header = TRUEtells R to treat the first row as column names.colClassesforces R to read specific column types. This helps avoid weird guesses.
Example: A table like this:
| score | gender |
|---|---|
| 85 | M |
| 92 | F |
gets loaded like so:
> alumnos <- read.table("scores.txt", header = TRUE,
colClasses = c("numeric", "factor"))
⸻
⚓ Tip: Always Know Where Ye Are
Use getwd() to find yer current working directory:
> getwd()
Set a new working directory with:
> setwd("C:/Users/YourName/Documents/Rprojects")
Better yet: use RStudio Projects, which handle this automatically.
⸻
🪝 Shortcuts and Safety
- Use file.choose() to open a file dialog:
> datos <- read.table(file.choose(), header = TRUE)
- Always check your file path spelling, slashes, and extensions.
- Prefer forward slashes / or file.path() for paths that work on any platform.