cs01_data <- read_csv("data/cs01_combined.csv") |>
mutate(treatment = fct_relevel(treatment, "Placebo", "5.9% THC (low dose)"))07-cs01-eda
CS01: Biomarkers of Recent Use (EDA)
Q&A
A: I’m not sure I totally understand the question. But, you can control color on all geoms. The specific parameter may differ, but all color can be controlled.
A: Yup! https://www.data-to-viz.com/
A: I break it into those who typically attend class, those who occassionally attend class, and those who don’t attend class and then randomly assign within those groups. This will be announced this week.
Course Announcements
Due Dates:
- Lab 04 due Fri (11:59 PM)
- HW 02 due Sun (11:59 PM)
- 🔘 Lecture Participation survey “due” after class
Note: cs01 groups will (for real this time) be sent out tomorrow
Suggested Reading
Agenda
- CS01
- Instructions
- Previous Projects
- CS01 EDA
- Exploratory Data Analysis (EDA)
CS01
CS01 Instructions
Instructions are on course website.
Note:
- Deliverables: Full report (.html) + general communication
- Common Deductions
Example Case Study
See & Discuss: https://cogs137-fa26.github.io/cogs137-fa26/content/cs/cs-example.html
Feedback & Scores
Feedback to other students here
You cannot see the projects, but can read all of the comments and see the associated score. Also, note that the same row is not the same group.
. . .
Common comments:
- context/explanation/guidance/lacking
- missing citations
- failure to introduce/describe the data
- making statements without evidence
- need to edit for cohesiveness, story, clarity
An (Example) Rubric
This is NOT the rubric for your case study, but it will be similar:

Notes
- Lots of code/plots will be provided here
- You are free to include any of it in your own case study (no attribution needed)
- You probably should NOT include all of them in your final report
- For any of the “basic” plots you include in your report, you’ll want to clean them up/improve their design.
- Your final report should be polished from start to finish
Exploratory Data Analysis (EDA)
EDA
The process of really getting to “know” your data:
- calculating descriptive statistics (min, mean, median, max, etc.)
- univariate plots (histograms, densityplots, barplots) - distributions of single variables
- bivariate plots (scatterplots, boxplots) - relationships between variables
. . .
Notes:
- Not every plot you generate in this process has to end up in your final report, but each plot should help you learn
- Every plot should NOT be beautiful. Save that time for the ones you ultimately use to communicate your findings
- There is NOT a formula for carrying out EDA. You stop once you understand your data fully.
- Lab03 is to get you started. Three plots is probably not enough for you to be fully comfortable with these data.
Data & Files
Question
Which compound, in which matrix, and at what cutoff is the best biomarker of recent use?
Our Datasets
Three matrices:
- Blood (WB): 8 compounds; 190 participants
- Oral Fluid (OF): 7 compounds; 192 participants
- Breath (BR): 1 compound; 191 participants
. . .
Variables:
ID| participants identifierTreatment| placebo, 5.90%, 13.40%Group| Occasional user, Frequent userTimepoint| indicator of which point in the timeline participant’s collection occurredtime.from.start| number of minutes from consumption- & measurements for individual compounds
The Data
Reading in the csv provided in lab03/cs01:
Time windows & compounds
Defined once in src/cs01_functions.R (and used by clean_cs01(), which made the time windows in this file):
# ==== Time windows ============================================================
# Windows (minutes from start of smoking) differ by matrix, following the paper.
# `cut()` intervals are right-closed: (0, 30] is "0-30 min"; anything <= 0 is
# pre-smoking; the last window is open-ended.
cs01_windows <- list(
WB = list(breaks = c(-Inf, 0, 30, 70, 100, 180, 210, 240, 270, 300, Inf),
labels = c("pre-smoking", "0-30 min", "31-70 min", "71-100 min",
"101-180 min", "181-210 min", "211-240 min",
"241-270 min", "271-300 min", "301+ min")),
OF = list(breaks = c(-Inf, 0, 30, 90, 180, 210, 240, 270, Inf),
labels = c("pre-smoking", "0-30 min", "31-90 min", "91-180 min",
"181-210 min", "211-240 min", "241-270 min", "271+ min")),
BR = list(breaks = c(-Inf, 0, 40, 90, 180, 210, 240, 270, Inf),
labels = c("pre-smoking", "0-40 min", "41-90 min", "91-180 min",
"181-210 min", "211-240 min", "241-270 min", "271+ min"))
)
# The first window after smoking, for each matrix
cs01_early_windows <- c("0-30 min", "0-40 min")
# Compounds measured (not every matrix has every compound)
cs01_compounds <- c("cbn", "cbd", "thc", "thcoh", "thccooh", "thccooh_gluc",
"cbg", "thcv", "thca_a")CS01: EDA
Single Variable (basic) plots
For a single compound…
ggplot(cs01_data, aes(x=thc)) +
geom_histogram()
. . .
But, we have three different matrices…
ggplot(cs01_data, aes(x=thc)) +
geom_histogram() +
facet_wrap(~fluid_type)
But what if we consider our experiment/the structure of our data? We have three different matrices…and a whole bunch of compounds. With wide data, it’s not easy to plot these distributions, so you may want to pivot those data….
# Wide -> long: one row per measurement of one compound
cs01_to_long <- function(df) {
df |>
pivot_longer(any_of(cs01_compounds),
names_to = "compound", values_to = "value")
}cs01_long <- cs01_to_long(cs01_data)We select the compound columns by name (cs01_compounds), not by position (e.g. 7:15), so this keeps working if the columns move.
. . .
Distributions across all compounds:
ggplot(cs01_long, aes(x=value)) +
geom_histogram() +
facet_wrap(~compound)
…but this still doesn’t get at the differences between matrices and compound.
. . .
Plotting some of these data…
cs01_long |>
mutate(group_compound=paste0(fluid_type, ": ", compound)) |>
ggplot(aes(x=value)) +
geom_histogram() +
facet_wrap(~group_compound, scales="free")
THC & Frequency
cs01_long |>
filter(compound == "thc") |>
ggplot(aes(x=group, y=value)) +
geom_boxplot() +
facet_wrap(~fluid_type, scales="free")
THC & Treatment Group
cs01_long |>
filter(compound == "thc") |>
ggplot(aes(x=treatment, y=value)) +
geom_boxplot() +
facet_wrap(~fluid_type, scales="free")
Focus on a specific timepoint…
cs01_long |>
filter(compound == "thc", timepoint %in% cs01_early_windows) |>
ggplot(aes(x=treatment, y=value)) +
geom_boxplot() +
facet_wrap(~fluid_type, scales="free")
At this point…
We start to get a sense of the data with these quick and dirty plots, but we’re really only scratching the surface of what’s going on in these data.
. . .
These data require a lot of exploration due to the number of compounds, multiple matrices, and data over time aspects.
Day 2 · Wed 10/21
Functions & working across time windows.
Q&A
A: CS01 is due next Sunday, after week 5 (11/01)
Course Announcements
Due Dates:
- Lab 04 due Fri (11:59 PM)
- HW 02 due Sun (11:59 PM)
- 🔘 Lecture Participation survey “due” after class
Notes:
- CS01 groups were sent out - GH repo + email
- hw01 scores (Canvas) /feedback (GH Issue) were posted
Brief Aside: User-Defined Functions
You should consider writing a function whenever you’ve copied and pasted a block of code more than twice -Hadley
function_name <- function(input){
# operations using input
}. . .
For example…
double_value <- function(val){
val * 2
}. . .
To use/execute:
double_value(3)[1] 6
Additional resource: https://r4ds.hadley.nz/functions
Compounds across time
Shared colors & theme (used by every CS01 plot):
# ==== Plotting ================================================================
cs01_colors <- c("Frequent user" = "#19831C", "Occasional user" = "#A27FC9")
theme_cs01 <- function(base_size = 12) {
theme_classic(base_size = base_size) +
theme(legend.position = "bottom",
legend.title = element_blank(),
panel.grid = element_blank(),
plot.title.position = "plot",
strip.background = element_blank())
}Our first user-defined function takes the data and the matrix as arguments:
# Every measurement over time for one matrix, one panel per compound
plot_scatter_time <- function(df_long, matrix) {
df_long |>
filter(fluid_type == matrix, !is.na(time_from_start), !is.na(value)) |>
ggplot(aes(x = time_from_start, y = value, color = group)) +
geom_point() +
facet_wrap(~compound, scales = "free") +
scale_color_manual(values = cs01_colors) +
labs(title = matrix, x = "Time From Start (min)", y = "Measurement") +
theme_cs01()
}plot_scatter_time(cs01_long, "WB")
plot_scatter_time(cs01_long, "OF")
plot_scatter_time(cs01_long, "BR")
- We do NOT have clear delineations in time
- This means there could be multiple measurements from a single individual within a specified timepoint (i.e. “0-30 min”)
- We wouldn’t want to include duplicate measures from the same individual within timepoint
- We wouldn’t have known this without looking at our data…why EDA is necessary
Dropping Duplicates (w/n time window)
# Keep one measurement per person per matrix per time window (the first one)
drop_dups <- function(df) {
df |>
filter(!is.na(timepoint)) |>
distinct(fluid_type, timepoint, id, .keep_all = TRUE)
}cs01_nodups <- drop_dups(cs01_data). . .
Now to pivot_longer that…
cs01_nodups_long <- cs01_to_long(cs01_nodups)While I drop duplicates after making the plots above, you and your group will want to think about when it should be done for telling the clearest story. The order we do things in EDA is not typically the order in which we communicate information.
Group Differences: Frequency of Use
One function for both “frequency of use” and “treatment” comparisons: x says what to compare.
# Boxplots at the first post-smoking window for one matrix.
# x: the variable to compare (e.g., group or treatment), unquoted
plot_boxplots <- function(df_long, matrix, x) {
df_long |>
filter(fluid_type == matrix,
timepoint %in% cs01_early_windows,
!is.na(value)) |>
ggplot(aes(x = {{ x }}, y = value, fill = group)) +
geom_boxplot(outlier.shape = NA, alpha = 0.6) +
geom_point(position = position_jitterdodge(jitter.width = 0.2, jitter.height = 0),
size = 0.8, color = "gray40") +
facet_wrap(~compound, scales = "free") +
scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) +
scale_y_continuous(limits = c(0, NA), expand = expansion(mult = c(0, 0.1))) +
scale_fill_manual(values = cs01_colors) +
labs(title = matrix, x = NULL, y = "Measurement (ng/mL)") +
theme_cs01()
}plot_boxplots(cs01_nodups_long, "WB", x = group)
plot_boxplots(cs01_nodups_long, "OF", x = group)
plot_boxplots(cs01_nodups_long, "BR", x = group)
- Certain compounds show different values between frequent and infrequent users. Worth considering what that means for our ultimate goal
- Breath at this first timepoint likely not very helpful…what about other timepoints?
Group Differences: Treatment
Same function as before…just a different x:
plot_boxplots(cs01_nodups_long, "WB", x = treatment)plot_boxplots(cs01_nodups_long, "WB", x = treatment)
plot_boxplots(cs01_nodups_long, "OF", x = treatment)
plot_boxplots(cs01_nodups_long, "BR", x = treatment)
- Argument for combining treatment groups?
- Shared
ggplot2settings live intheme_cs01()andcs01_colors, and one function makes both sets of boxplots. When you find yourself copy-pasting plot code, that’s a function waiting to happen. - These last two sets of plots have only focused on that first timepoint. You’ll probably want to look beyond that.
Day 3 · Fri 10/23
Sensitivity, specificity & choosing cutoffs: the core of the CS01 question.
Q&A
A: Good question! For case studies, we want this to be an effective report. Commenting every line would make teh code less readable, so we’ll want to avoid that. Instead, we’ll want a bit of text before the code to explain at a high-level what was done and then let the code speak for itself. Comments here or there are great!
Course Announcements
Due Dates:
- Lab 04 due today (10/23) (11:59 PM)
- HW 02 due Sun (11:59 PM)
- 🔘 Lecture Participation survey “due” after class
Notes:
- CS01 group work in class planned for Monday - plan to come and work with your group
Some Metrics
Sensitivity & Specificity
Sensitivity | the ability of a test to correctly identify patients with a disease/trait/condition. \[TP/(TP + FN)\]
. . .
Specificity | the ability of a test to correctly identify people without the disease/trait/condition. \[TN/(TN + FP)\]
. . .
❓ For this analysis, do you care more about sensitivity? about specificity? equally about both?
What is a TP here? TN? FP? FN?
Post-smoking (cutoff > 0)
- TP = THC group, value >= cutoff
- FN = THC group, value < cutoff
- FP = Placebo group, value >= cutoff
- TN = Placebo group, value < cutoff
. . .
Pre-smoking
Cannot be a TP or FN before consuming…
- TP = 0
- FN = 0
- FP = value >= cutoff
- TN = value < cutoff
The Code to come
This is beyond code I would expect you all to be able to write yourself. It’s here so that 1) you can make these calculations and interpret the results, 2) because we have a wide range of background and experience. I want everyone to get as much as they can out of this course, and 3) I do want you all to talk to one another. That’s one reason you all are in groups for case studies.
Calculating Sensitivity and Specificity
For every matrix × compound × time window × cutoff, count TPs, FNs, FPs, and TNs.
- Start with the long, de-duplicated data (one row per person × window × compound)
- Copy each row once per cutoff (
cross_join()) - Label each row: used (THC group, after smoking)? detected (value ≥ cutoff)?
group_by()+summarize()to count…exactly what you learned in thedplyrnotes
# ==== Sensitivity & specificity ===============================================
# For every matrix x compound x time window x cutoff:
# "used" = received THC AND sample taken after smoking
# "detected" = value at or above the cutoff
# Pre-smoking samples count as true negatives/false positives only.
sens_spec <- function(df_long, cutoffs = c(0.5, 1, 2, 5, 10)) {
df_long |>
filter(!is.na(value), !is.na(timepoint)) |>
cross_join(tibble(cutoff = cutoffs)) |>
mutate(used = treatment != "Placebo" & timepoint != "pre-smoking",
detected = value >= cutoff) |>
group_by(fluid_type, compound, timepoint, cutoff) |>
summarize(TP = sum(used & detected),
FN = sum(used & !detected),
FP = sum(!used & detected),
TN = sum(!used & !detected),
.groups = "drop") |>
mutate(N = TP + FN + FP + TN,
sensitivity = TP / (TP + FN),
specificity = TN / (TN + FP),
ppv = TP / (TP + FP),
npv = TN / (TN + FN),
efficiency = (TP + TN) / N)
}Reminder: Currently, states have laws on the books from zero tolerance (detection of any level) to 5ng/mL THC
cs01_ss <- sens_spec(cs01_nodups_long, cutoffs = c(0.5, 1, 2, 5, 10))
cs01_ss# A tibble: 720 × 14
fluid_type compound timepoint cutoff TP FN FP TN N
<chr> <chr> <chr> <dbl> <int> <int> <int> <int> <int>
1 BR thc 0-40 min 0.5 124 1 16 47 188
2 BR thc 0-40 min 1 124 1 16 47 188
3 BR thc 0-40 min 2 124 1 16 47 188
4 BR thc 0-40 min 5 124 1 16 47 188
5 BR thc 0-40 min 10 124 1 16 47 188
6 BR thc 181-210 min 0.5 7 51 1 31 90
7 BR thc 181-210 min 1 7 51 1 31 90
8 BR thc 181-210 min 2 7 51 1 31 90
9 BR thc 181-210 min 5 7 51 1 31 90
10 BR thc 181-210 min 10 7 51 1 31 90
# ℹ 710 more rows
# ℹ 5 more variables: sensitivity <dbl>, specificity <dbl>, ppv <dbl>,
# npv <dbl>, efficiency <dbl>
cs01_ss |>
filter(compound == "thc", cutoff == 5) |>
select(fluid_type, timepoint, TP, FN, FP, TN, sensitivity, specificity)# A tibble: 26 × 8
fluid_type timepoint TP FN FP TN sensitivity specificity
<chr> <chr> <int> <int> <int> <int> <dbl> <dbl>
1 BR 0-40 min 124 1 16 47 0.992 0.746
2 BR 181-210 min 7 51 1 31 0.121 0.969
3 BR 211-240 min 12 53 1 33 0.185 0.971
4 BR 241-270 min 4 53 0 26 0.0702 1
5 BR 271+ min 10 53 2 24 0.159 0.923
6 BR 41-90 min 18 30 1 40 0.375 0.976
7 BR 91-180 min 24 64 0 30 0.273 1
8 BR pre-smoking 0 0 6 185 NaN 0.969
9 OF 0-30 min 128 1 3 60 0.992 0.952
10 OF 181-210 min 36 29 0 37 0.554 1
# ℹ 16 more rows
Plot Results
Note: requires library(patchwork)
# Sensitivity (left) & specificity (right) across time windows, one line per cutoff
plot_cutoffs <- function(ss, fluid, cpd, title = fluid) {
df <- ss |>
filter(fluid_type == fluid, compound == cpd) |>
mutate(timepoint = factor(timepoint, levels = cs01_windows[[fluid]]$labels),
cutoff = factor(cutoff))
base <- function(y, ylab) {
ggplot(df |> filter(!is.na({{ y }})),
aes(x = timepoint, y = {{ y }} * 100, color = cutoff, group = cutoff)) +
geom_line(linewidth = 1.2) +
geom_point() +
scale_y_continuous(limits = c(0, 100)) +
scale_x_discrete(drop = FALSE) +
# colorblind-friendly sequential palette (darker = higher cutoff)
scale_color_viridis_d(name = "Cutoff (ng/mL)", end = 0.85, direction = -1) +
labs(x = "Time Window", y = ylab) +
theme_cs01() +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
}
(base(sensitivity, "Sensitivity (%)") + labs(title = paste0(title, ": ", toupper(cpd)))) +
base(specificity, "Specificity (%)") +
patchwork::plot_layout(guides = "collect") &
theme(legend.position = "bottom", legend.title = element_text())
}plot_cutoffs(cs01_ss, "WB", "thc", title = "Blood")
plot_cutoffs(cs01_ss, "OF", "thc", title = "Oral Fluid")
plot_cutoffs(cs01_ss, "BR", "thc", title = "Breath")
- This is only THC
- For five semi-random cutoffs
- There are other compounds and other cutoffs to consider
- Breath THC is measured in pg/pad (not ng/mL), so these cutoffs don’t separate anything for breath (the lines overlap). What cutoffs would make sense there?
Possible Extensions
Our current question asks for a single compound…and you’ll need to decide that.
. . .
…but you could imagine a world where more than one compound or more than one matrix could be measured at the roadside.
. . .
So:
- combination of the oral fluid and blood that would better predict recent use? (For example if an officer stopped a driver and got a high oral fluid, but could not get a blood sample for a couple of hours and got a relatively low result would this predict recent use better than blood (or OF) alone?
- Is there a ratio of OF/blood that predicts recent use?
- Machine learning model to determine optimal combination of measurements/cutoffs to detect recent use?
. . .
Things to keep in mind:
- some matrices are easier to get at the roadside
- time from use matters (trying to detect recent use)
- we may not care equally about sensitivity and specificity
cs01: what to do now?
- Communicate with your group!
- Discuss possible extensions
- Make a plan; figure out who’s doing what; set deadlines
- Implement the plan!
What has to be done:
- Question | include in qmd; add extension if applicable
- Background | summarize and add to what was discussed in classed
- Data
- Describe data & variables
- Data wrangling | likely copy + paste from notes/lab; add explanation as you go
- Analysis
- EDA | likely borrowing parts from notes and modifying/adding more in to tell your story; be sure to include interpretations of output & guide the reader
- Drawing conclusions to answer the question
- Extension | must be completed
- Discussion & Conclusion | summarize; discuss limitations
- Proofread | ensure it makes sense from top to bottom
- General Audience communication (submit on Canvas; 1 submission per group)
Avoid the temptation to assign “Analysis” to one group member. You’ll all likely have to contribute here.
Collaborating on GitHub
- Be sure to pull changes every time you sit down to work
- Avoid working on the same part of the same file as another teammate OR work in separate files and combine at the end
- push your changes once you’re ready to add them to the group
Recap
- Can you explain/describe the plots generated in the context of these data?
- Can you generate EDA plots of your own for these data
- Can you understand/work through the more complicated code provided (even if you couldn’t have come up with it on your own)
- Can you describe sensitivity? Specificity?
- Can you explain how TP, TN, FP, and FN were calculated/defined in this experiment?
- Can you describe the code used to carry out the calculations?
- Can you interpret the results from these data?