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:
Syntax
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
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")
Login to try C/C++/Java/PHP code in the editor
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
- Reading a file with
read.csv("people.csv")from the wrong working directory, so R sayscannot open file; checkgetwd(). - Reading a semicolon-separated file with
read.csv, whenread.csv2orsep = ";"is needed. - Not noticing numbers stored as text because of a stray character in the column, so
class(df$age)ischaracter.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: