Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Data Frames and Data Wrangling

Reading and Writing Data in R

Import and export data in R. Use read.csv() and write.csv(), readr, readxl and jsonlite, handle missing-value codes and encodings, and save objects with saveRDS().

Real analysis starts with real files: a CSV export from a database, an Excel workbook from a colleague, a JSON response from a web service. R can read almost anything. This lesson covers the common formats, the options that fix the usual import problems, and how to save your own results.

Because R cannot run in this page, the examples either read a small text string (with text =, so you can paste them straight into R) or show a file name you would replace with your own.

Where are my files?

R looks for relative paths in the working directory. Check it with getwd(). If you work in an RStudio Project (see Install R and RStudio), it is the project folder, so "data/sales.csv" works on any computer. Paths use forward slashes / even on Windows. file.exists("data/sales.csv") tests whether a file is there, and list.files("data") shows what a folder holds.

CSV files with base R

CSV (comma-separated values) is the most common exchange format. read.csv() reads one into a data frame:

R
sales <- read.csv("data/sales.csv")

To try the function without a file, give it text:

R
csv_text <- "name,score
Ana,90
Ben,85
Cleo,NA"

df <- read.csv(text = csv_text)
df
#>   name score
#> 1  Ana    90
#> 2  Ben    85
#> 3 Cleo    NA

str(df)
#> 'data.frame':	3 obs. of  2 variables:
#>  $ name : chr  "Ana" "Ben" "Cleo"
#>  $ score: int  90 85 NA

The first line is used as column names, types are guessed from the values, and NA becomes a missing value. Always run str() after importing.

Useful arguments:

Argument Purpose Example
header First row holds names? (default TRUE) header = FALSE
sep Separator character sep = ";"
na.strings Text that means missing na.strings = c("", "n/a", "-")
skip Skip lines before the data skip = 2
nrows Read only the first n rows nrows = 100
colClasses Set column types yourself colClasses = c(id = "character")
stringsAsFactors Convert text to factors stringsAsFactors = TRUE
encoding Character encoding fileEncoding = "UTF-8"

Many countries use a semicolon as the separator and a comma as the decimal mark. read.csv2() reads that style, and read.delim() reads tab-separated files.

The stray text problem

A single non-numeric entry makes the whole column text:

R
bad <- read.csv(text = "id,height
1,170
2,n/a
3,165")

class(bad$height)
#> [1] "character"

good <- read.csv(text = "id,height
1,170
2,n/a
3,165", na.strings = "n/a")

class(good$height)
#> [1] "integer"

This is the practical side of the type rules from Data Types and Coercion. Declare missing-value codes when you read, rather than cleaning up later.

Writing CSV files

R
write.csv(df, "scores.csv", row.names = FALSE)

row.names = FALSE stops R from adding a useless column of 1, 2, 3 that shows up as an extra column when the file is read again. The file contains:

Text
"name","score"
"Ana",90
"Ben",85
"Cleo",NA

The readr package (tidyverse)

readr offers faster functions with more predictable behavior. They return tibbles, never turn text into factors, and print the column types they chose:

R
library(readr)

sales <- read_csv("data/sales.csv")
write_csv(sales, "data/sales-clean.csv")
Base R readr
read.csv() read_csv()
read.csv2() read_csv2()
read.delim() read_tsv()
write.csv() write_csv()

You control types with col_types, for example read_csv("f.csv", col_types = cols(id = col_character(), date = col_date())), and missing codes with na = c("", "n/a"). read_csv() is much faster on large files; for huge data look at data.table::fread() or the arrow package.

Excel files

The readxl package reads .xlsx and .xls without needing Excel installed:

R
library(readxl)

excel_sheets("data/report.xlsx")                    # sheet names
sheet <- read_excel("data/report.xlsx", sheet = "Q1")
sheet <- read_excel("data/report.xlsx", range = "B2:E20")

To write Excel files use writexl::write_xlsx(df, "out.xlsx").

Plain text and lines

R
lines <- readLines("notes.txt")      # one string per line
writeLines(c("first", "second"), "out.txt")

readLines() is the tool for logs and unstructured text. You will process the result with the functions in String Manipulation.

JSON

Data from web services is often JSON. The jsonlite package converts it to R structures:

R
library(jsonlite)

json <- '{"name": "Ana", "scores": [90, 85]}'
obj <- fromJSON(json)
obj$name
#> [1] "Ana"

obj$scores
#> [1] 90 85

A JSON object becomes a list, and an array of equal-shaped objects becomes a data frame. toJSON(df) goes the other way.

Saving R objects: RDS and RData

CSV loses information: factor levels, column types and list structure. To save an R object exactly as it is, use RDS:

R
saveRDS(sales, "data/sales.rds")
sales <- readRDS("data/sales.rds")

saveRDS() stores one object; you choose its name when reading it back. save(a, b, file = "work.RData") stores several named objects, and load("work.RData") restores them under their original names. RDS is preferred because load() can overwrite existing variables without warning. RDS files are R-specific and compressed, so use CSV when you share data with other tools.

A safe import routine

  1. Read with explicit na.strings and, when needed, colClasses.
  2. Run str(df), summary(df) and head(df).
  3. Check dim(df) against the number of lines you expect.
  4. Fix types (as.numeric(), as.Date()), then continue.
  5. Keep the original file untouched; write cleaned results to a new file.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use row.names = FALSE in write.csv()?

    Without it, a column of 1, 2, 3 is added and appears as an unwanted column when you re-read the file.
  2. 2. A column that should be numeric is read as text because of the value "n/a". What fixes it at import?

    na.strings tells R which strings mean missing, so the column stays numeric.
  3. 3. Which format saves an R object exactly, including factor levels and types?

    RDS stores the R object itself. CSV is text and loses type details.
  4. 4. Which function reads a file where fields are separated by semicolons and decimals use commas?

    read.csv2() is configured for that European style; read_csv2() is the readr equivalent.

Summary

  • Read CSV with read.csv() or readr::read_csv(); write with write.csv(..., row.names = FALSE) or write_csv().
  • Set na.strings and colClasses to prevent wrong column types, then check with str().
  • Use readxl for Excel, jsonlite for JSON, readLines() for raw text.
  • Save R objects with saveRDS() and read them with readRDS().
  • Use RStudio Projects and relative paths so your code runs anywhere.

Next: Subsetting Data Frames