Skip to content
AgileLogics
6 min read

Importing and Exporting Data

Prerequisites: Data frames, Packages

Real analysis starts with getting data into R. The most common format is CSV (comma-separated values) — plain text where each line is a row and commas separate the columns.

Base R: read.csv

csv_text <- "name,age,city
Ada,36,London
Linus,28,Helsinki
Grace,45,New York"

people <- read.csv(text = csv_text)
people
str(people)
   name age     city
1   Ada  36   London
2 Linus  28 Helsinki
3 Grace  45 New York
'data.frame':	3 obs. of  3 variables:
 $ name: chr  "Ada" "Linus" "Grace"
 $ age : int  36 28 45
 $ city: chr  "London" "Helsinki" "New York"

Normally you pass a file path: read.csv("data/people.csv"). (The text = argument here just lets the example run without a file.) The path is relative to your working directory — in an RStudio Project, the project folder.

readr: read_csv

The tidyverse's readr package is faster, gives clearer messages about what it found, and returns a tibble (next lesson):

library(readr)

people <- read_csv(I("name,age,city
Ada,36,London
Linus,28,Helsinki"), show_col_types = FALSE)
people
# A tibble: 2 × 3
  name    age city
  <chr> <dbl> <chr>
1 Ada      36 London
2 Linus    28 Helsinki

I("...") marks literal data instead of a file name. With a real file: read_csv("data/people.csv"). readr prints the column types it guessed; show_col_types = FALSE hides that message once you've checked them.

Handling messy files

Common arguments (for both functions, with slightly different names):

  • na = c("", "NA", "n/a") — which text means "missing".
  • skip = 2 — skip lines at the top (titles, notes).
  • col_types (readr) — state column types explicitly instead of guessing.
  • For semicolon-separated files (common in Europe), use read.csv2 or read_csv2.

Other formats

  • Excel — readxl::read_excel("file.xlsx", sheet = "Sales").
  • JSON — jsonlite::fromJSON(...) (its own lesson later).
  • SPSS, Stata, SAS — the haven package.
  • Databases — the DBI package (Level 3).

Writing data

write.csv(people, "output/people.csv", row.names = FALSE)
readr::write_csv(people, "output/people.csv")
saveRDS(people, "output/people.rds")   # R's own format: keeps types exactly

Common mistakes

  • cannot open file 'data.csv': No such file or directory — check your working directory with getwd(), and use an RStudio Project so paths stay consistent.
  • Not checking column types after importing. A numeric column read as text usually means a stray non-numeric value somewhere.