CHAPTER 13
Beginner
Data Import and Export
Updated: May 18, 2026
5 min read
# CHAPTER 13
Data Import and Export in R
1. Chapter Introduction
Real-world data arrives in dozens of formats — Excel spreadsheets, JSON APIs, SQL databases, Stata files. This chapter builds a complete data import/export toolkit that handles every major data format.2. CSV and Text Import (readr)
r
3. Excel Import (readxl)
r
4. JSON Import (jsonlite)
r
5. Database Connection (DBI)
r
6. Common Mistakes
-
Excel date import as numbers: Excel stores dates as numbers since 1900.
read_excel()handles this automatically, butread.csv()of an Excel-exported CSV may give numbers like45000. Useas.Date(x, origin="1899-12-30").
-
JSON nested structure not flattening:
fromJSON("nested.json")may return a complex nested list. Useflatten=TRUEortidyr::unnest()to expand into a flat data frame.
7. MCQs
Question 1
read_csv() returns?
Question 2
excel_sheets("file.xlsx") returns?
Question 3
fromJSON(url) can read data from?
Question 4
dbGetQuery(con, sql) returns?
Question 5
problems(df) after read_csv shows?
Question 6
dbWriteTable() with overwrite=TRUE?
Question 7
toJSON(x, pretty=TRUE) formats output?
Question 8
col_factor(levels=c("A","B")) in read_csv?
Question 9
read_excel(range="B2:G50") reads?
Question 10
SQLite advantage over MySQL for analysis?
8. Interview Questions
- Q: How do you connect R to a MySQL database and run queries?
- Q: How do you import a multi-sheet Excel file into R?
9. Summary
Data import ecosystem:readr (CSV/TSV, fastest), readxl (Excel), jsonlite (JSON/APIs), DBI + RMySQL/RSQLite (databases). Always check problems() after read_csv(). Use col_types for type safety. JSON: fromJSON(flatten=TRUE) for nested data. Database: dbGetQuery() for queries, dbWriteTable() to export results. Use parameterized queries to prevent SQL injection.