R Tutorial

Data Import & Export

Reading CSV, Excel, and SQL data into R

Getting Data In

R can read data from almost any source. The most common format is CSV.
r
# Base R
data <- read.csv("data.csv")

# Tidyverse (Faster and smarter)
library(readr)
data <- read_csv("data.csv")

Supported Formats

FormatLibraryFunction
CSVreadrread_csv()
Excelreadxlread_excel()
JSONjsonlitefromJSON()
SQLDBIdbGetQuery()
SPSS/Statahavenread_spss()

Exporting Data

Saving your results is just as easy.
r
write_csv(data, "results.csv")
Wait! If you want to save an R object and its exact state (including types and factor levels), use the .rds format.
r
saveRDS(data, "my_data.rds")
new_data <- readRDS("my_data.rds")

Connecting to Databases

R can connect directly to production databases (PostgreSQL, MySQL, BigQuery, etc.). This allows you to pull the exact data you need without manual exports.

Summary

TermDescription
CSVComma-Separated Values
HeaderThe first row containing column names
DelimiterThe character separating values (comma, tab, etc.)
Working DirUse getwd() and setwd() to manage where R looks for files
Best ForGetting raw data into your analytical pipeline
Logic"Data accessibility"
SafetyModern functions automatically handle malformed rows
Modernreadr and vroom are significantly faster than base R
StandardAlways use stringsAsFactors = FALSE (default in R 4.0+)
IdentityR's ability to handle "Messy" data is world-class