R — Data Import
CSV files
# Base R
data <- read.csv("data.csv")
data <- read.csv("data.csv", stringsAsFactors = FALSE)
# readr
library(readr)
data <- read_csv("data.csv")
data <- read_tsv("data.tsv")
data <- read_delim("data.txt", delim = "|")
Excel files
library(readxl)
# Read Excel
data <- read_excel("data.xlsx")
data <- read_excel("data.xlsx", sheet = "Sheet1")
data <- read_excel("data.xlsx", range = "A1:D10")
# List sheets
excel_sheets("data.xlsx")
JSON files
library(jsonlite)
# Read JSON
data <- fromJSON("data.json")
# Write JSON
toJSON(data, pretty = TRUE, auto_unbox = TRUE)
write(toJSON(data, auto_unbox = TRUE), "output.json")
Database
library(DBI)
library(RSQLite)
# Connect
con <- dbConnect(SQLite(), "database.db")
# Read table
data <- dbReadTable(con, "users")
# Query
data <- dbGetQuery(con, "SELECT * FROM users WHERE age > 25")
# Disconnect
dbDisconnect(con)
Mini Practice
Write R code that:
- Reads a CSV file with readr
- Reads an Excel file with readxl
- Reads JSON with jsonlite
- Queries a SQLite database
Up Next
In the next lesson, you'll learn about Data Export — writing data to files.
Related Topics
Frequently Asked Questions about Data Import
What is Data Import in R?
Data Import is a fundamental concept in R. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Data Import?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Data Import.
Why is Data Import important in R?
Data Import is essential for R development. Understanding this concept will help you write better code and solve real-world problems more effectively.