R Read CSV Files

A CSV (Comma-Separated Values) file is the most common format for sharing data. Each line represents one row, and values within a row are separated by commas. R reads CSV files into data frames with a single function call, making them instantly ready for analysis.

What a CSV File Looks Like

students.csv:
────────────────────────────────────────
name,age,score,city
Anita,22,88,Delhi
Ravi,25,72,Mumbai
Seema,21,45,Chennai
Kiran,23,95,Pune
────────────────────────────────────────
Row 1:  Header row (column names)
Rows 2+: Data rows

Reading a CSV with read.csv()

students <- read.csv("students.csv")
print(students)
#    name age score    city
# 1 Anita  22    88   Delhi
# 2  Ravi  25    72  Mumbai
# 3 Seema  21    45 Chennai
# 4 Kiran  23    95    Pune

str(students)
# 'data.frame': 4 obs. of 4 variables:
#  $ name : chr  "Anita" "Ravi" "Seema" "Kiran"
#  $ age  : int  22 25 21 23
#  $ score: int  88 72 45 95
#  $ city : chr  "Delhi" "Mumbai" "Chennai" "Pune"

Key Arguments of read.csv()

Argument           Default    Description
──────────────────────────────────────────────────────────────────
file               (required) File path or URL
header             TRUE       First row = column names?
sep                ","        Column separator character
stringsAsFactors   FALSE      Convert strings to factors?
na.strings         "NA"       What strings to treat as NA
skip               0          How many rows to skip at top
nrows              -1         Max rows to read (-1 = all)
colClasses         NULL       Force specific column types
encoding           "unknown"  File character encoding

Common Reading Scenarios

# File with semicolons instead of commas (European format)
df <- read.csv2("data.csv")   # uses ";" as separator

# File with tabs
df <- read.delim("data.txt")  # uses "\t" as separator

# Custom separator
df <- read.csv("data.csv", sep="|")

# Skip the first 2 rows (metadata/comments)
df <- read.csv("data.csv", skip=2)

# Treat "N/A", "-", and "" as missing
df <- read.csv("data.csv", na.strings=c("N/A","-","","NULL"))

Reading from a URL

url <- "https://raw.githubusercontent.com/datasets/gdp/master/data/gdp.csv"
world_gdp <- read.csv(url)
head(world_gdp, 3)

Faster Reading with read_csv() from readr

library(readr)

students <- read_csv("students.csv")
# Faster, better type detection, returns a tibble
read.csv vs read_csv:
──────────────────────────────────────────────────────
Feature             read.csv (base)   read_csv (readr)
──────────────────────────────────────────────────────
Speed               Slower            ~10x faster
Type detection      Basic             Smarter
Output type         data.frame        tibble
stringsAsFactors    Used to be TRUE   Never converts
Progress bar        No                Yes (large files)

Checking What You Read

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

nrow(data)          # number of rows
ncol(data)          # number of columns
head(data)          # first 6 rows
tail(data)          # last 6 rows
str(data)           # structure and types
summary(data)       # statistics per column
colSums(is.na(data)) # count NAs in each column

Setting the Working Directory

# Always set working directory before reading files
setwd("C:/Users/YourName/R_Projects/data")

# Or use a relative path
data <- read.csv("data/students.csv")

# Or use the full absolute path
data <- read.csv("C:/Users/YourName/Downloads/students.csv")

Handling Common Problems

Problem                         Solution
────────────────────────────────────────────────────────────────────
File not found                  Check setwd() and file name spelling
Wrong column count              File may use different separator; check sep
All columns are one column      Wrong separator; use sep=";" or sep="\t"
Dates read as character         Convert: as.Date(col, "%Y-%m-%d")
Numbers read as character       Check for commas in numbers: "1,000"
First row not headers           Set header=FALSE, then name manually

Reading CSV files is the most common way to get data into R for analysis. A few lines of code load thousands of rows instantly, and the resulting data frame is ready for cleaning, visualization, and modeling.

Leave a Comment

Your email address will not be published. Required fields are marked *