Working with Databases in R
DBI and SQL
Connecting and Querying
DBI provides a consistent interface. RSQLite (for SQLite), RMySQL/RMariaDB (for MySQL), RPostgres (for PostgreSQL).
library(DBI); library(RSQLite)
con <- dbConnect(RSQLite::SQLite(), 'vidaara.db')
dbWriteTable(con, 'students', df, overwrite=TRUE)
dbGetQuery(con, 'SELECT subject, AVG(score) as avg FROM students GROUP BY subject')
dbDisconnect(con)
# See the code example above and adapt it to your data. # Always check your output with str() and head().
dbplyr — dplyr on Databases
dbplyr translates dplyr code to SQL automatically. Use tbl() to create a reference, collect() to fetch results.
library(dplyr)
tbl(con, 'students') |>
filter(score >= 90) |>
group_by(subject) |>
summarise(n=n(), mean_score=mean(score, na.rm=TRUE)) |>
collect() # execute SQL and return data frame
# See the code example above and adapt it to your data. # Always check your output with str() and head().