0
0
R-programmingHow-ToBeginner ยท 3 min read

How to Use read_csv in readr for Reading CSV Files in R

Use read_csv() from the readr package to read CSV files into R as tibbles. Simply provide the file path as a string to read_csv(), and it will import the data with automatic parsing of columns.
๐Ÿ“

Syntax

The basic syntax of read_csv() is simple and user-friendly. You provide the path to your CSV file as a string. Optional arguments let you customize how the file is read, such as specifying column types or skipping rows.

  • file: The path to the CSV file.
  • col_names: Whether the first row contains column names (default is TRUE).
  • col_types: Specify column data types manually.
  • skip: Number of lines to skip before reading data.
r
read_csv(file, col_names = TRUE, col_types = NULL, skip = 0)
๐Ÿ’ป

Example

This example shows how to read a CSV file named data.csv using read_csv(). It automatically detects column types and returns a tibble, which is a modern data frame with better printing.

r
library(readr)

# Example CSV content saved as data.csv:
# name,age,score
# Alice,30,85.5
# Bob,25,90.0
# Carol,27,88.0

# Read the CSV file
my_data <- read_csv("data.csv")

# Print the imported data
print(my_data)
Output
# A tibble: 3 ร— 3 name age score <chr> <dbl> <dbl> 1 Alice 30 85.5 2 Bob 25 90 3 Carol 27 88
โš ๏ธ

Common Pitfalls

Common mistakes when using read_csv() include:

  • Not specifying the correct file path, causing a file not found error.
  • Assuming the first row is data when it actually contains headers (use col_names = TRUE to fix).
  • Incorrect column type guesses, which can be fixed by manually setting col_types.

Here is an example of a wrong and right way to read a CSV with no headers:

r
# Wrong: assumes headers but file has none
read_csv("no_header.csv")

# Right: specify col_names = FALSE
read_csv("no_header.csv", col_names = FALSE)
๐Ÿ“Š

Quick Reference

ArgumentDescriptionDefault
filePath to the CSV file to readRequired
col_namesUse first row as column namesTRUE
col_typesManually specify column typesNULL (auto-detect)
skipNumber of lines to skip before reading0
naStrings to interpret as missing values"" (empty string)
โœ…

Key Takeaways

Use read_csv() from readr to easily import CSV files as tibbles in R.
Provide the file path as a string and adjust col_names if your file has no headers.
read_csv() guesses column types automatically but you can specify them with col_types.
Check your file path carefully to avoid file not found errors.
Use the Quick Reference table to remember common arguments and defaults.