If you already think in SQL, you can query an R data frame with it directly, without setting up a database server. I use the duckdb package here, which runs the database inside your R session.
How do I run a SQL query on a data frame in R?
Open a duckdb connection, give the data frame a table name with duckdb_register(), and send the query with dbGetQuery(). The result comes back as a data frame. This block runs on its own:
library(DBI)
library(duckdb)
library(nycflights13)
con <- dbConnect(duckdb())
duckdb_register(con, "flights", flights)
dbGetQuery(con, "
SELECT origin,
COUNT(*) AS flights,
ROUND(AVG(dep_delay), 1) AS mean_delay
FROM flights
GROUP BY origin
ORDER BY mean_delay DESC
")
## origin flights mean_delay
## 1 EWR 120835 15.1
## 2 JFK 111279 12.1
## 3 LGA 104662 10.3
The data is nycflights13, 336,776 flights that left New York City in 2013, from the US Bureau of Transportation Statistics. I ran this on R 4.6.1 with duckdb 2.0.0 and DBI 1.3.0.
Join two data frames with SQL
Register the second data frame under its own name and join as usual:
duckdb_register(con, "airlines", airlines)
dbGetQuery(con, "
SELECT a.name, COUNT(*) AS flights
FROM flights f
JOIN airlines a ON f.carrier = a.carrier
GROUP BY a.name
ORDER BY flights DESC
LIMIT 5
")
## name flights
## 1 United Air Lines Inc. 58665
## 2 JetBlue Airways 54635
## 3 ExpressJet Airlines Inc. 54173
## 4 Delta Air Lines Inc. 48110
## 5 American Airlines Inc. 32729
Missing values are NULL
An NA in R becomes NULL in SQL. COUNT(*) counts every row, COUNT(column) skips the missing ones, and AVG() skips them too, so you don’t need na.rm = TRUE:
dbGetQuery(con, "
SELECT COUNT(*) AS all_rows,
COUNT(dep_delay) AS with_delay,
COUNT(*) - COUNT(dep_delay) AS missing
FROM flights
")
## all_rows with_delay missing
## 1 336776 328521 8255
Register again after you change the data frame
The registered table is the data frame as it was when you registered it. If you change the data frame afterwards, the query still sees the old values until you register it again with overwrite = TRUE. Without that argument, duckdb stops with an error because the name is taken:
sales <- data.frame(amount = c(1, 2, 3))
duckdb_register(con, "sales", sales)
sales$amount <- sales$amount * 10
dbGetQuery(con, "SELECT SUM(amount) AS total FROM sales")
## total
## 1 6
duckdb_register(con, "sales", sales, overwrite = TRUE)
dbGetQuery(con, "SELECT SUM(amount) AS total FROM sales")
## total
## 1 60
Close the connection when you are done:
dbDisconnect(con)
The older sqldf package does the same job in one call, sqldf("SELECT ..."), and uses SQLite by default. I use duckdb here because the same connection can also read CSV and Parquet files.