0Pricing
R Academy · Lesson

Reading CSV Files with read_csv()

Import delimited files with column type guessing, skipping, and encoding options.

Why readr Instead of Base R?

Base R has read.csv(), but the readr package's read_csv() is faster, returns a tibble (not a data frame), provides better default type guessing, and gives informative messages about the column types it detected.

library(readr)

# read_csv() vs read.csv():
# 1. Returns a tibble (prints nicely, faster subsetting)
# 2. Does NOT convert strings to factors by default
# 3. Shows column specification message
# 4. Faster for large files

# Example with a simple inline CSV:
df <- read_csv('name,score,grade
Alice,85,B
Bob,92,A
Carol,78,C')

print(df)
print(class(df))

read_csv() from a File Path

The most common usage: pass a file path string to read_csv(). The function automatically detects the delimiter as a comma, reads the first row as headers, and guesses column types from the first 1000 rows.

library(readr)

# Reading from a file path (illustrative — file not present)
# df <- read_csv('data/sales_2024.csv')

# Reading from a URL also works:
# df <- read_csv('https://example.com/data.csv')

# Using a literal inline string for demonstration:
df <- read_csv('region,q1,q2,q3
East,100,120,115
West,200,195,210
North,80,85,90')

print(df)

All lessons in this course

  1. Reading CSV Files with read_csv()
  2. Parsing TSV and Fixed-Width Files
  3. Importing Excel Files with readxl
  4. Writing Data to Multiple Formats
← Back to R Academy