Archived edition: You are reading the 2024 edition of Learn Crime Mapping with R. Read the current edition.

Appendix A — Functions for reading data into R

R can read data in many different formats. Different functions (often from different packages) are needed to read files of different formats. These are some of the functions needed to read common types of file used in data analysis, including spatial data formats.

Functions for reading data into R
Data file type Package Function Can load compressed files? Can load files from URL?

Comma-separated values (.csv)

readr

read_csv() (data from English-speaking countries) or read_csv2() (data from elsewhere)

yes

yes

Fixed-width files (usually .txt)

readr

read_fwf()

yes

yes

GeoJSON (.geojson)

sf

read_sf()

no

yes

GeoPackage (.gpkg)

sf

read_sf()

no

yes

Google Sheets

googlesheets4

read_sheet()

n/a

yes

HTML (.htm or .html)

xml2

read_html() (probably used with functions from the rvest package)

n/a

yes

JSON (.json)

jsonlite

read_json()

yes

yes

Microsoft Excel (.xlsx or .xls)

readxl

read_excel()

no

no

OpenDocument Spreadsheet (.ods)

readODS

read_ods()

no

yes

R Data (.rds)

readr

read_rds()

n/a

yes

SAS (.sas7bdat)

haven

read_sas()

yes

yes

Shapefile (.shp)

sf

read_sf()

no

no

SPSS Statistics (.sav)

haven

read_sav()

yes

yes

Stata (.dta)

haven

read_dta()

yes

yes

Tab-separated values (.tsv or .tab)

readr

read_tsv()

yes

yes

XML (usually .xml)

xml2

read_xml()

yes

yes