Learn R Programming  /  Import & Export  /  CSV Files

CSV Files

CSV (comma-separated values) is the simplest, most portable way to store tabular data. Base R can read and write CSV files with no extra packages required.

Writing a Data Frame to CSV

R Code
df <- data.frame(
  name  = c("Rafi", "Meera"),
  score = c(88, 92)
)

write.csv(df, "students.csv", row.names = FALSE)
💡 Tip
Always set row.names = FALSE unless you specifically want an extra unnamed column of row numbers written into the file - it is one of the most common CSV mistakes beginners run into.

Reading a CSV File

R Code
df2 <- read.csv("students.csv")
df2
str(df2)
Output
   name score
1  Rafi    88
2 Meera    92
'data.frame':	2 obs. of  2 variables:
 $ name : chr  "Rafi" "Meera"
 $ score: int  88 92

Useful read.csv() Arguments

R Code
# semicolon-delimited file, common in European locales
read.csv("data.csv", sep = ";")

# file has no header row
read.csv("data.csv", header = FALSE)

# keep text columns as plain character, not factor (R default since 4.0)
read.csv("data.csv", stringsAsFactors = FALSE)

Checking and Setting the Working Directory

File paths in read.csv()/write.csv() are relative to R\'s current working directory unless you give a full path.

R Code
getwd()                        # check current working directory
setwd("C:/Users/You/data")   # change it (Windows example)
⚠ Common Mistake
Error in file(file, \"rt\") : cannot open the connection almost always means R is looking in the wrong folder. Run getwd() first, or better, use an RStudio Project so relative paths always work correctly.

Advanced: Reading Only the Columns You Need

🚀 Advanced Example
For very large CSV files, reading everything into memory can be wasteful. colClasses lets you skip columns entirely by marking them NULL.
R Code
# skip the 2nd column entirely while reading
read.csv("big_data.csv", colClasses = c("character", "NULL", "numeric"))

Key Points

  • read.csv() and write.csv() work with zero extra packages.
  • Always use row.names = FALSE when writing, unless you want an extra index column.
  • Set stringsAsFactors = FALSE to keep text columns as character (this has been the default since R 4.0).
  • File-not-found errors usually mean the working directory is wrong - check with getwd().