library(dplyr)
library(magrittr)R and SQLite
This post compares R and SQL approaches to the same data questions. It is for anyone learning either language or interested in seeing how familiar data tasks translate between them.
Getting Started
The examples use practice questions from SQL Practice. We will load the data into R, create a temporary SQLite database, and work through each question in both languages.
Packages
For all my data queries and manipulation in R I will be using base R, dplyr, and magrittr.
To create a SQL database, and run SQL queries in R chunks I will be using a package called RSQLite.
# install.packages("RSQLite")
library(RSQLite)Warning: package 'RSQLite' was built under R version 4.5.2
Data
Data source: These examples use practice data from SQL Practice. The patient table contains a subset of 1,000 records used for this post.
The examples use three data sets:
patients: Which includes patient_id, first_name, last_name, gender, birth_date, city, province_id, allergies, height, and weight.
patients <- utils::read.csv('data/patients.csv')province_names: Which includes province_id, and province_name.
province_names <- utils::read.csv("data/province_names.csv")admissions: which includes patient_id, admission_date, discharge_date, diagnosis, attending_doctor_id
admissions <- utils::read.csv("data/admissions.csv")Database
Create an in-memory SQLite database with dbConnect() and SQLite(). It exists for this R session and does not change a database file.
hosp <- RSQLite::dbConnect(RSQLite::SQLite(),
":memory:")Use dbWriteTable() to add each data frame as a table in the database.
RSQLite::dbWriteTable(hosp,
"patients",
patients)
RSQLite::dbWriteTable(hosp,
"province_names",
province_names)
RSQLite::dbWriteTable(hosp,
"admissions",
admissions)Verify the three data sets are in the database using:
dbListTables()to list the tables within the hosp database.
RSQLite::dbListTables(hosp)[1] "admissions" "patients" "province_names"
1. Show the first ten rows of patients data.
Use head() to display the first ten patient records.
utils::head(patients, 10)Use SELECT * to choose all columns and LIMIT to return ten rows.
RSQLite::dbGetQuery(hosp,
"SELECT *
FROM patients
LIMIT 10"
)2. Show the total number of patients.
Use nrow() to count patient records and data.frame() to label the result.
base::data.frame("total_patients" = base::nrow(patients))Use COUNT(*) to count rows and AS to name the result.
RSQLite::dbGetQuery(hosp,
"SELECT COUNT(*) AS total_patients
FROM patients"
)3. Show first and last name as full_name.
Use paste0() to combine first and last names, then show the first ten results.
utils::head(
base::data.frame(
full_name = base::paste0(patients$first_name,
" ",
patients$last_name)),
10)Use || to join the names, AS to label the result, and LIMIT to show ten rows.
RSQLite::dbGetQuery(hosp,
"SELECT first_name || ' ' || last_name AS full_name
FROM patients
LIMIT 10"
)4. Show unique cities that are in province_id ‘NS’?
Filter to Nova Scotia, keep distinct cities, and rename the output column.
patients %>%
filter(province_id == "NS") %>%
distinct(city) %>%
rename(unique_cities = city) Use WHERE to filter to Nova Scotia and DISTINCT to return each city once.
dbGetQuery(hosp,
"SELECT DISTINCT(city) AS unique_cities
FROM patients
WHERE province_id IS 'NS'"
)5. Show the total number of male patients and the total number of female patients.
Display the two results in the same row.
Use which() and length() to count patients marked “M” and “F.”
base::data.frame(
male_count = base::length(base::which(patients$gender == 'M')),
female_count = base::length(base::which(patients$gender == 'F'))
)Use two filtered counts to return both totals in one row.
dbGetQuery(hosp,
"SELECT
(SELECT COUNT(*) FROM patients WHERE gender = 'M') AS male_count,
(SELECT COUNT(*) FROM patients WHERE gender = 'F') AS female_count")6. Show all allergies ordered by popularity. Remove NULL values from the query.
Exclude missing values and the literal string "NULL", count each allergy, and show the ten most common.
patients %>%
dplyr::filter(!is.na(allergies), allergies != "NULL") %>%
dplyr::group_by(allergies) %>%
dplyr::summarise(total_diagnosis = dplyr::n()) %>%
dplyr::arrange(dplyr::desc(total_diagnosis)) %>%
utils::head(10)Exclude missing values and the literal string 'NULL', then group and count allergies in descending order.
dbGetQuery(hosp,
"SELECT allergies,
COUNT(*) AS total_diagnosis
FROM patients
WHERE allergies IS NOT 'NULL' AND allergies IS NOT NULL
GROUP BY allergies
ORDER BY total_diagnosis DESC
LIMIT 10"
)7. Display the total number of patients for each province. Order by descending.
Join patients to province names, count patients in each province, and sort from highest to lowest.
base::merge(province_names, patients, by = "province_id") %>%
dplyr::group_by(province_name) %>%
dplyr::summarise(patient_count = dplyr::n()) %>%
dplyr::arrange(dplyr::desc(patient_count))Join the tables by province ID, then group and count patients by province.
RSQLite::dbGetQuery(hosp,
"SELECT province_name,
COUNT(*) AS patient_count
FROM patients pa
JOIN province_names pr ON pr.province_id = pa.province_id
GROUP BY pr.province_id
ORDER BY patient_count DESC")8. Show the provinces that have more patients identified as ‘M’ than ‘F’. Must only show full province_name.
Join the tables, count patients marked “M” and “F” in each province, and keep provinces where the first count is higher.
base::merge(province_names, patients, by = "province_id") %>%
dplyr::group_by(province_name) %>%
dplyr::summarise(male_count = sum(gender == "M", na.rm = TRUE),
female_count = sum(gender == "F", na.rm = TRUE),
.groups = "drop") %>%
dplyr::filter(male_count > female_count) %>%
dplyr::select(province_name)Join the tables and use HAVING to keep provinces with more patients marked “M” than “F.”
RSQLite::dbGetQuery(hosp,
"SELECT pr.province_name
FROM patients AS pa
JOIN province_names AS pr ON pa.province_id = pr.province_id
GROUP BY pr.province_id
HAVING
COUNT( CASE WHEN gender = 'M' THEN 1 END) >
COUNT( CASE WHEN gender = 'F' THEN 1 END)")9. Calculate the total cost per insurance group.
For this example, assume patients with even-numbered IDs have insurance. Assign a cost of $10 to each patient with insurance and $50 to each patient without insurance, then add the costs for each group. Count one cost per patient.
Use case_when() to assign insurance status and cost, then sum costs by group.
patients %>%
dplyr::mutate(
has_insurance = dplyr::case_when(
patient_id %% 2 == 0 ~ "Yes",
patient_id %% 2 != 0 ~ "No"
),cost_after_insurance = dplyr::case_when(
has_insurance == "Yes" ~ 10,
has_insurance == "No" ~ 50
)) %>%
group_by(has_insurance) %>%
summarise(cost_after_insurance = base::sum(cost_after_insurance))Use CASE to assign insurance status and cost, then sum costs by group.
RSQLite::dbGetQuery(hosp,
"SELECT
CASE WHEN patient_id % 2 = 0 Then 'Yes'
ELSE 'No'
END as has_insurance,
SUM(
CASE WHEN patient_id % 2 = 0 Then 10
ELSE 50
END
) AS cost_after_insurance
FROM patients
GROUP BY has_insurance;")10. We are looking for a specific patient. Pull all columns for the patient who matches the following criteria:
- First_name contains a ‘b’ after the first two letters.
- Identifies their gender as ‘F’
- Their weight would be between 50 kg and 70 kg
- Their patient_id is an odd number
- They are from the city ‘Burlington’
Filter by name, gender, weight, patient ID, and city. The name check ignores case, and the weight range includes both endpoints.
patients %>%
dplyr::filter(base::grepl("^.{2}b", first_name, ignore.case = TRUE),
gender == "F",
weight >= 50 & weight <= 70,
patient_id %%2==1,
city == "Burlington")Use LIKE and the other conditions to filter records. BETWEEN includes 50 and 70.
RSQLite::dbGetQuery(hosp,
"SELECT *
FROM patients
WHERE
first_name LIKE '__b%'
AND gender = 'F'
AND weight BETWEEN 50 AND 70
AND patient_id % 2 = 1
AND city = 'Burlington';")Bonus: Map patients by province
This map visualizes the patient counts from question 7. It uses a subset of the practice data, so it does not represent actual patient populations. Provinces and territories without matching records are shown as zero.
One benefit of R is its wide range of open-source packages. Packages like ggplot2 can help turn results into visualizations that make patterns easier to see, stories easier to share, and data more accessible to different audiences.
# Install these packages if needed:
# install.packages(c("ggplot2", "sf", "rnaturalearth"))
province_counts <- patients %>%
count(province_id, name = "patient_count")
canada <- rnaturalearth::ne_download(
scale = 50, type = "states", category = "cultural",
returnclass = "sf"
) %>%
filter(grepl("^CA-", iso_3166_2)) %>%
mutate(province_id = sub("^CA-", "", iso_3166_2))Reading 'ne_50m_admin_1_states_provinces_lakes.zip' from naturalearth...
stopifnot(all(province_counts$province_id %in% canada$province_id))
canada <- canada %>%
left_join(province_counts, by = "province_id") %>%
mutate(patient_count = dplyr::coalesce(patient_count, 0L))
province_plot <- ggplot2::ggplot(canada) +
ggplot2::geom_sf(ggplot2::aes(fill = patient_count))
AI use: I used AI to help revise this post, correct code examples, and create the map. I guided the changes and reviewed the results.
Close the database connection when finished:
RSQLite::dbDisconnect(hosp)