← Back to R Course | Chapter 8: Data Manipulation | Lesson 1 of 7

Reading CSV Files

Reading a CSV file loads a plain-text table, such as a spreadsheet export, into R as a data frame. It is like opening a file of rows and columns to work with.

In this page:

  1. Reading CSV Files
Syntax
r
df <- read.csv("file.csv")
df <- read.csv("file.csv", header = TRUE, stringsAsFactors = FALSE)

Reading CSV Files

read.csv("file.csv") reads a comma-separated file directly into a data frame, automatically inferring column types from the data. It's the most common way to load tabular data into R for analysis.

header = TRUE (the default) treats the first row as column names.

Note: Pass stringsAsFactors = FALSE (the modern default in recent R versions) if you want text columns to stay as character rather than becoming factors.

Example: Reading CSV Files

markup
csv_text <- "name,age\nAlice,30\nBob,25"
writeLines(csv_text, "people.csv")

df <- read.csv("people.csv")
print(df)
cat(class(df$age), "\n")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Reading a file with read.csv("people.csv") from the wrong working directory, so R says cannot open file; check getwd().
  2. Reading a semicolon-separated file with read.csv, when read.csv2 or sep = ";" is needed.
  3. Not noticing numbers stored as text because of a stray character in the column, so class(df$age) is character.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.