Differential Abundance
A differential abundance test asks, for every assay on the panel, whether two groups of
samples differ in NPX, and then controls the false discovery rate across all of those
tests. This page runs it on Day 0 plasma from the MGH COVID-19 cohort of
Filbin et al. 2021, severe disease against
non-severe disease. You first fit a Welch t-test for each assay and then a linear model that
adjusts for age. The R tab uses olink_ttest() from
OlinkAnalyze and
limma. The Python tab uses SciPy and statsmodels.
The comparison
Section titled “The comparison”The paper defines severity by Acuity max, the worst state a patient reached in the 28
days after enrollment. Acuity 1 is death and 2 is intubation, and the paper groups those
two as severe against 3 to 5, which cover oxygen, a hospital stay without oxygen, and
discharge. Only COVID-positive subjects enter the test, and only their Day 0 sample, so
each subject gives one row. The code reads the three workbooks, links the Olink
Public ID to the clinical subject, and reshapes the wide NPX sheet to one row per sample
and assay. The NPX & QC page explains that reshape, and
the Olink NPX format page describes the long layout.
The data below come from Bánk Fenyves’s version 2 deposit for Filbin and colleagues’ 2021 study, under CC BY 4.0. This lesson reshapes the NPX workbook, joins assay and clinical annotations, and selects Day 0 COVID-positive subjects for the comparison.
suppressPackageStartupMessages({ library(readxl) library(dplyr) library(tidyr) library(OlinkAnalyze) library(limma) library(jsonlite)})
data_dir <- "/opt/data/mgh_covid_olink"
# One row per sample and one column per OlinkID. Missing NPX is the text NA.npx_wide <- read_excel(file.path(data_dir, "olink_proteomics.xlsx"), na = "NA")# Sheet 2A has a title row above its header.assays <- read_excel( file.path(data_dir, "supplemental_table_2_olink_assays.xlsx"), sheet = "2A-Olink-Assay", skip = 1)clinical <- read_excel(file.path(data_dir, "clinical_metadata.xlsx"), sheet = "Subject-level metadata")
# The subject ID is the part of the Olink Public ID before the underscore.samples <- npx_wide |> filter(Day == "0") |> transmute(SampleID = `Public ID`, subject = as.numeric(sub("_.*", "", `Public ID`))) |> inner_join(clinical, by = c(subject = "Public ID")) |> filter(COVID == 1) |> transmute( SampleID, subject, acuity_max = `Acuity max`, Severity = factor(if_else(acuity_max <= 2, "Severe", "Non-severe"), levels = c("Severe", "Non-severe")), age_group = factor(`Age cat`) )
count(samples, Severity, acuity_max)table(severity = samples$Severity, age_group = samples$age_group)
# Long format: one row per sample and assay, with the assay annotation.npx_long <- npx_wide |> filter(Day == "0") |> select(-Day) |> rename(SampleID = `Public ID`) |> pivot_longer(starts_with("OID"), names_to = "OlinkID", values_to = "NPX") |> inner_join(samples, by = "SampleID") |> inner_join(select(assays, OlinkID, Assay, UniProt, Panel, Panel_Version, LOD), by = "OlinkID")cat("rows:", nrow(npx_long), " assays:", n_distinct(npx_long$OlinkID), " samples:", n_distinct(npx_long$SampleID), "\n")# A tibble: 5 × 3 Severity acuity_max n <fct> <dbl> <int>1 Severe 1 422 Severe 2 673 Non-severe 3 1334 Non-severe 4 405 Non-severe 5 23 age_groupseverity 1 2 3 4 5 Severe 4 14 27 37 27 Non-severe 28 52 61 28 27rows: 435845 assays: 1429 samples: 305import json
import numpy as npimport pandas as pdimport statsmodels.api as smfrom scipy import statsfrom statsmodels.stats.multitest import multipletests
DATA_DIR = "/opt/data/mgh_covid_olink"
npx_wide = pd.read_excel(f"{DATA_DIR}/olink_proteomics.xlsx")assays = pd.read_excel( f"{DATA_DIR}/supplemental_table_2_olink_assays.xlsx", sheet_name="2A-Olink-Assay", skiprows=1,)clinical = pd.read_excel( f"{DATA_DIR}/clinical_metadata.xlsx", sheet_name="Subject-level metadata",).rename(columns={"Public ID": "subject"})
# Day holds 0, 3, 7 and the text E, so read it as text.day0 = npx_wide[npx_wide["Day"].astype(str) == "0"].copy()day0["subject"] = day0["Public ID"].str.split("_").str[0].astype(int)
samples = day0[["Public ID", "subject"]].merge(clinical, on="subject")samples = samples[samples["COVID"] == 1].rename( columns={"Public ID": "sample_id", "Acuity max": "acuity_max", "Age cat": "age_group"})samples["severity"] = np.where( samples["acuity_max"] <= 2, "Severe", "Non-severe")samples = samples[["sample_id", "subject", "acuity_max", "severity", "age_group"]].reset_index(drop=True)
print(samples.groupby(["severity", "acuity_max"]).size().to_string())print(pd.crosstab(samples["severity"], samples["age_group"]))
olink_ids = [column for column in npx_wide if column.startswith("OID")]npx_long = ( day0.melt(id_vars="Public ID", value_vars=olink_ids, var_name="OlinkID", value_name="NPX") .rename(columns={"Public ID": "sample_id"}) .merge(samples, on="sample_id") .merge(assays[["OlinkID", "Assay", "UniProt", "Panel", "LOD"]], on="OlinkID"))print("rows:", len(npx_long), " assays:", npx_long["OlinkID"].nunique(), " samples:", npx_long["sample_id"].nunique())severity acuity_maxNon-severe 3 133 4 40 5 23Severe 1 42 2 67age_group 1 2 3 4 5severityNon-severe 28 52 61 28 27Severe 4 14 27 37 27rows: 435845 assays: 1429 samples: 305305 subjects enter the test, 109 severe and 196 non-severe. Look hard at the age table, where group 1 is the youngest and group 5 the oldest. Only 4 of the 109 severe patients are in group 1, against 28 of the 196 non-severe patients, while group 4 holds 37 severe and 28 non-severe patients. Any protein that rises with age will look like a severity marker in a test that ignores age. The clinical file codes age as five groups, not as years, so the model below can adjust for the group only.
Filter assays on the LOD
Section titled “Filter assays on the LOD”The public file gives one LOD per assay. An assay below its LOD in most samples measures background, and testing it adds a hypothesis to the correction without adding information. This page keeps an assay when at least half of the 305 samples lie above its LOD. The rule ignores the severity labels on purpose, because a filter that looks at the groups favors assays that already differ and biases the false discovery rate. Inside a kept assay, the values below the LOD stay as the file reports them.
# The share of the 305 samples whose NPX is above the assay LOD.detection <- npx_long |> group_by(OlinkID, Assay, Panel) |> summarise(above_lod = mean(NPX > LOD, na.rm = TRUE), .groups = "drop")
min_above_lod <- 0.5kept_ids <- detection$OlinkID[detection$above_lod >= min_above_lod]npx_kept <- filter(npx_long, OlinkID %in% kept_ids)
detection |> mutate(kept = above_lod >= min_above_lod) |> count(Panel, kept) |> pivot_wider(names_from = kept, values_from = n, names_prefix = "kept_") |> as.data.frame()cat("kept", length(kept_ids), "of", nrow(detection), "assays\n") Panel kept_FALSE kept_TRUE1 CARDIOMETABOLIC 50 3182 INFLAMMATION 74 2913 NEUROLOGY 83 2454 ONCOLOGY 69 299kept 1153 of 1429 assays# The share of the 305 samples whose NPX is above the assay LOD. A missing# NPX counts in neither the numerator nor the denominator.npx_long["above_lod"] = (npx_long["NPX"] > npx_long["LOD"]).where( npx_long["NPX"].notna())detection = ( npx_long.groupby(["OlinkID", "Assay", "Panel"])["above_lod"] .mean() .reset_index())
MIN_ABOVE_LOD = 0.5kept_ids = detection.loc[ detection["above_lod"] >= MIN_ABOVE_LOD, "OlinkID"].tolist()npx_kept = npx_long[npx_long["OlinkID"].isin(kept_ids)]
print( pd.crosstab(detection["Panel"], detection["above_lod"] >= MIN_ABOVE_LOD) .rename(columns={False: "kept_FALSE", True: "kept_TRUE"}))print("kept", len(kept_ids), "of", len(detection), "assays")above_lod kept_FALSE kept_TRUEPanelCARDIOMETABOLIC 50 318INFLAMMATION 74 291NEUROLOGY 83 245ONCOLOGY 69 299kept 1153 of 1429 assaysThe filter keeps 1,153 of the 1,429 assays. Neurology loses the most, 83 assays, and keeps 245.
Welch t-tests
Section titled “Welch t-tests”A Welch t-test compares two means without assuming that the groups share a variance, which
suits groups of 109 and 196 patients. olink_ttest() runs t.test() once per OlinkID and
adjusts the p-values with Benjamini-Hochberg across every assay it tested. Before that, it
runs check_npx(), which looks for a plate ID and a QC warning column. The public workbook
has neither, so the code adds both as NA. That passes the check. It does not replace the
plate QC that the file cannot give you.
# check_npx() looks for a plate ID, a QC warning and a panel version. The# public file has no plate ID and no QC warning, so those columns are NA.ttest_input <- npx_kept |> mutate(PlateID = NA_character_, QC_Warning = NA_character_, Panel_Version = as.character(Panel_Version))check_log <- check_npx(ttest_input)
# Severity is a factor with Severe first, so estimate is Severe minus# Non-severe. olink_ttest() runs t.test(), which is Welch by default, and# adjusts the p-values with Benjamini-Hochberg.welch <- olink_ttest(ttest_input, variable = "Severity", check_log = check_log)
welch_sig <- filter(welch, Adjusted_pval < 0.05)cat("assays tested:", nrow(welch), "\n")cat("significant at FDR 0.05:", nrow(welch_sig), "\n")cat(" higher in severe:", sum(welch_sig$estimate > 0), "\n")cat(" lower in severe:", sum(welch_sig$estimate < 0), "\n")cat(" distinct Assay names:", n_distinct(welch_sig$Assay), "\n")
welch |> head(10) |> transmute(Assay, OlinkID, Panel, estimate = round(estimate, 3), t = round(statistic, 2), df = round(parameter, 1), p = signif(p.value, 3), fdr = signif(Adjusted_pval, 3)) |> as.data.frame() |> print(row.names = FALSE)
dir.create("outputs", showWarnings = FALSE)write.csv(select(welch, OlinkID, statistic, p.value, Adjusted_pval), "outputs/olink_differential_welch_r.csv", row.names = FALSE)assays tested: 1153significant at FDR 0.05: 734 higher in severe: 687 lower in severe: 47 distinct Assay names: 726 Assay OlinkID Panel estimate t df p fdr KRT19 OID20596 INFLAMMATION 1.887 10.23 183.2 1.01e-19 1.16e-16 IL6 OID20101 CARDIOMETABOLIC 1.749 9.61 205.9 2.68e-18 1.51e-15 IL6 OID20911 NEUROLOGY 1.745 9.52 206.3 4.86e-18 1.51e-15 IL6 OID21276 ONCOLOGY 1.712 9.49 209.9 5.25e-18 1.51e-15 IL6 OID20563 INFLAMMATION 1.720 9.42 200.1 1.15e-17 2.64e-15 PTX3 OID20570 INFLAMMATION 0.902 8.98 233.1 9.46e-17 1.82e-14 CHI3L1 OID20399 CARDIOMETABOLIC 1.617 8.94 209.5 2.09e-16 3.45e-14 TRIAP1 OID21403 ONCOLOGY 1.098 8.87 182.6 6.46e-16 8.45e-14 LTBP2 OID20254 CARDIOMETABOLIC 1.025 8.82 193.2 6.60e-16 8.45e-14 IL1RL1 OID20250 CARDIOMETABOLIC 1.158 8.78 173.7 1.49e-15 1.57e-13# One row per assay and one column per sample, in the order of samples.matrix = npx_kept.pivot(index="OlinkID", columns="sample_id", values="NPX")matrix = matrix[samples["sample_id"]]is_severe = (samples["severity"] == "Severe").to_numpy()values = matrix.to_numpy()
# equal_var=False is the Welch test. nan_policy="omit" drops missing NPX.welch_result = stats.ttest_ind( values[:, is_severe], values[:, ~is_severe], axis=1, equal_var=False, nan_policy="omit",)welch = pd.DataFrame({ "OlinkID": matrix.index, "estimate": (np.nanmean(values[:, is_severe], axis=1) - np.nanmean(values[:, ~is_severe], axis=1)), "statistic": welch_result.statistic, "df": welch_result.df, "p_value": welch_result.pvalue,})welch["fdr"] = multipletests(welch["p_value"], method="fdr_bh")[1]welch = welch.merge(assays[["OlinkID", "Assay", "Panel"]], on="OlinkID")welch = welch.sort_values("p_value", kind="stable").reset_index(drop=True)
welch_sig = welch[welch["fdr"] < 0.05]print("assays tested:", len(welch))print("significant at FDR 0.05:", len(welch_sig))print(" higher in severe:", int((welch_sig["estimate"] > 0).sum()))print(" lower in severe:", int((welch_sig["estimate"] < 0).sum()))print(" distinct Assay names:", welch_sig["Assay"].nunique())
top = welch.head(10)[["Assay", "OlinkID", "Panel"]].copy()top["estimate"] = welch["estimate"].head(10).round(3)top["t"] = welch["statistic"].head(10).round(2)top["df"] = welch["df"].head(10).round(1)top["p"] = welch["p_value"].head(10).map("{:.3g}".format)top["fdr"] = welch["fdr"].head(10).map("{:.3g}".format)print(top.to_string(index=False))
# The R tab ran first and wrote its full table.welch_r = pd.read_csv("outputs/olink_differential_welch_r.csv")both = welch.merge(welch_r, on="OlinkID", suffixes=("", "_r"))gap_t = np.abs(both["statistic"] - both["statistic_r"]).max()gap_p = np.abs(both["p_value"] - both["p.value"]).max()print(f"largest absolute difference from R: t {gap_t:.1e}, p {gap_p:.1e}")assays tested: 1153significant at FDR 0.05: 734 higher in severe: 687 lower in severe: 47 distinct Assay names: 726 Assay OlinkID Panel estimate t df p fdr KRT19 OID20596 INFLAMMATION 1.887 10.23 183.2 1.01e-19 1.16e-16 IL6 OID20101 CARDIOMETABOLIC 1.749 9.61 205.9 2.68e-18 1.51e-15 IL6 OID20911 NEUROLOGY 1.745 9.52 206.3 4.86e-18 1.51e-15 IL6 OID21276 ONCOLOGY 1.712 9.49 209.9 5.25e-18 1.51e-15 IL6 OID20563 INFLAMMATION 1.720 9.42 200.1 1.15e-17 2.64e-15 PTX3 OID20570 INFLAMMATION 0.902 8.98 233.1 9.46e-17 1.82e-14CHI3L1 OID20399 CARDIOMETABOLIC 1.617 8.94 209.5 2.09e-16 3.45e-14TRIAP1 OID21403 ONCOLOGY 1.098 8.87 182.6 6.46e-16 8.45e-14 LTBP2 OID20254 CARDIOMETABOLIC 1.025 8.82 193.2 6.6e-16 8.45e-14IL1RL1 OID20250 CARDIOMETABOLIC 1.158 8.78 173.7 1.49e-15 1.57e-13largest absolute difference from R: t 5.1e-14, p 2.4e-14734 of the 1,153 assays differ at FDR 0.05, and 687 of them are higher in severe patients. That is a count of assays, not of proteins. CXCL8, IL6 and TNF are measured once on each of the four Explore panels, and the four IL6 assays fill ranks 2 to 5 with differences between 1.712 and 1.749 NPX. The agreement says the IL6 signal does not depend on the panel, and it also means the 734 assays name 726 distinct proteins. KRT19 leads with a difference of 1.887 NPX. NPX is a log2 scale, so one unit is a twofold change in concentration.
The Python tab prints the same table. Over all 1,153 assays, the largest gap from the R results is 5.1e-14 for a t-statistic and 2.4e-14 for a p-value.
A linear model with age
Section titled “A linear model with age”A linear model for each assay, NPX ~ severe + age_group, estimates the severity
difference within age groups. In R, lmFit() fits every assay in one call, and eBayes()
then pulls each residual variance toward a common prior before it computes a moderated
t-statistic. The ordinary least squares t-statistic comes from the same fit, and that is
the value the Python tab gets from one statsmodels OLS fit per assay.
# Assays in rows and samples in columns, in the order of samples.npx_matrix <- npx_kept |> select(OlinkID, SampleID, NPX) |> pivot_wider(names_from = SampleID, values_from = NPX)expr <- as.matrix(npx_matrix[, samples$SampleID])rownames(expr) <- npx_matrix$OlinkID
# severe is 1 for Acuity max 1 or 2. Age group 1, 20 to 34, is the baseline.design <- model.matrix( ~ severe + age_group, data = mutate(samples, severe = as.integer(Severity == "Severe")))fit <- lmFit(expr, design)
# The ordinary t-statistic of each per-assay least squares fit.ordinary_t <- fit$coefficients[, "severe"] / (fit$stdev.unscaled[, "severe"] * fit$sigma)ordinary_p <- 2 * pt(-abs(ordinary_t), df = fit$df.residual)ordinary_fdr <- p.adjust(ordinary_p, method = "BH")
# eBayes() shrinks each assay variance toward a common prior.fit_eb <- eBayes(fit)cat("prior df:", round(fit_eb$df.prior, 2), " residual df:", median(fit$df.residual), "\n")moderated <- topTable(fit_eb, coef = "severe", number = Inf, sort.by = "none")
welch_fdr <- setNames(welch$Adjusted_pval, welch$OlinkID)[rownames(expr)]cat("significant at FDR 0.05\n")cat(" Welch t-test: ", sum(welch_fdr < 0.05), "\n")cat(" OLS with age: ", sum(ordinary_fdr < 0.05), "\n")cat(" limma with age: ", sum(moderated$adj.P.Val < 0.05), "\n")table(welch = welch_fdr < 0.05, ols = ordinary_fdr < 0.05)table(ols = ordinary_fdr < 0.05, limma = moderated$adj.P.Val < 0.05)
moderated |> mutate(OlinkID = rownames(moderated)) |> left_join(select(assays, OlinkID, Assay), by = "OlinkID") |> arrange(P.Value) |> head(10) |> transmute(Assay, OlinkID, logFC = round(logFC, 3), t = round(t, 2), p = signif(P.Value, 3), fdr = signif(adj.P.Val, 3)) |> print(row.names = FALSE)prior df: 3.73 residual df: 299significant at FDR 0.05 Welch t-test: 734 OLS with age: 548 limma with age: 546 olswelch FALSE TRUE FALSE 410 9 TRUE 195 539 limmaols FALSE TRUE FALSE 604 1 TRUE 3 545 Assay OlinkID logFC t p fdr KRT19 OID20596 1.612 9.34 2.17e-18 2.50e-15 IL6 OID20101 1.602 8.81 1.01e-16 5.24e-14 IL6 OID20911 1.607 8.75 1.51e-16 5.24e-14 EZR OID21017 0.559 8.70 2.11e-16 5.24e-14 IL6 OID20563 1.574 8.69 2.27e-16 5.24e-14 IL6 OID21276 1.565 8.63 3.49e-16 6.71e-14 IL1RL1 OID20250 1.028 8.32 3.01e-15 4.96e-13 DDAH1 OID21299 0.785 8.18 8.01e-15 1.16e-12 AGER OID20756 1.024 8.08 1.58e-14 2.02e-12 POLR2F OID21283 0.757 8.00 2.60e-14 3.00e-12def fit_ols(npx_values, design): """Fit one assay by ordinary least squares.
Args: npx_values: NPX of one assay, one value per sample. design: The design matrix, one row per sample.
Returns: A tuple of the coefficient, t-statistic and p-value of severe. """ fit = sm.OLS(npx_values, design, missing="drop").fit() return (fit.params["severe"], fit.tvalues["severe"], fit.pvalues["severe"])
# severe is 1 for Acuity max 1 or 2. Age group 1, 20 to 34, is the baseline.design = pd.get_dummies(samples["age_group"], prefix="age_group", drop_first=True, dtype=float)design.insert(0, "severe", is_severe.astype(float))design = sm.add_constant(design)design.index = samples["sample_id"]
ols_rows = [ (olink_id, *fit_ols(matrix.loc[olink_id], design)) for olink_id in matrix.index]ols = pd.DataFrame(ols_rows, columns=["OlinkID", "coef", "t", "p_value"])ols["fdr"] = multipletests(ols["p_value"], method="fdr_bh")[1]
welch_fdr = welch.set_index("OlinkID").loc[ols["OlinkID"], "fdr"].to_numpy()print("significant at FDR 0.05")print(" Welch t-test: ", int((welch_fdr < 0.05).sum()))print(" OLS with age: ", int((ols["fdr"] < 0.05).sum()))print(pd.crosstab(welch_fdr < 0.05, ols["fdr"].to_numpy() < 0.05, rownames=["welch"], colnames=["ols"]))
top_ols = ( ols.merge(assays[["OlinkID", "Assay"]], on="OlinkID") .sort_values("p_value", kind="stable") .head(10))top_ols["coef"] = top_ols["coef"].round(3)top_ols["t"] = top_ols["t"].round(2)top_ols["p_value"] = top_ols["p_value"].map("{:.3g}".format)top_ols["fdr"] = top_ols["fdr"].map("{:.3g}".format)print(top_ols[["Assay", "OlinkID", "coef", "t", "p_value", "fdr"]] .to_string(index=False))significant at FDR 0.05 Welch t-test: 734 OLS with age: 548ols False TruewelchFalse 410 9True 195 539 Assay OlinkID coef t p_value fdr KRT19 OID20596 1.612 9.30 3.18e-18 3.66e-15 IL6 OID20101 1.602 8.76 1.43e-16 6.2e-14 EZR OID21017 0.559 8.74 1.73e-16 6.2e-14 IL6 OID20911 1.607 8.71 2.15e-16 6.2e-14 IL6 OID20563 1.574 8.65 3.21e-16 7.4e-14 IL6 OID21276 1.565 8.59 4.91e-16 9.44e-14IL1RL1 OID20250 1.028 8.29 3.81e-15 6.27e-13 DDAH1 OID21299 0.785 8.16 9.11e-15 1.31e-12 AGER OID20756 1.024 8.05 1.98e-14 2.54e-12POLR2F OID21283 0.757 7.99 2.92e-14 3.36e-12Age takes a large share of the signal. The count falls from 734 assays to 548 with OLS and 546 with limma. 195 assays pass the Welch test and fail once age enters the model, while 9 go the other way, and the KRT19 difference shrinks from 1.887 to 1.612 NPX. The moderation itself changes little here. The prior carries 3.73 degrees of freedom against 299 residual degrees of freedom per assay, so each assay’s own variance dominates, and OLS and limma agree on 545 assays. limma earns its keep when each group holds a handful of samples, and this cohort holds hundreds. The model’s top ten keeps KRT19, IL6 and IL1RL1 and brings in EZR, DDAH1, AGER and POLR2F.
Compare with the paper
Section titled “Compare with the paper”Filbin et al. fit a linear mixed model to days 0, 3 and 7 together, with severity, time and their interaction, and with covariates for age, gender, ethnicity and seven comorbidities. They report 251 proteins that differ between severe and non-severe patients at Day 0. The public clinical file holds no gender and no ethnicity, so that model cannot be rebuilt from it, and the counts above do not compare one to one with 251.
The direction of the top hits does agree. The paper names IL-6, IL-1RL1, PTX3, IL-1RN, KRT19 and TRIAP1 among the strongest weighted proteins of its Day 0 severity classifier. Five of those six are in the Welch top ten here, and each is higher in severe patients. AGER encodes RAGE, which the paper reports as raised at Day 0 in severe patients. None of this says whether a protein drives severity or follows from it.
Both tabs write the values they share to a metrics file. The gate compares counts exactly and statistics, coefficients and p-values to a relative tolerance of 1e-9.
# The best assay of each of the first five distinct proteins.top_ids <- welch |> distinct(Assay, .keep_all = TRUE) |> head(5) |> pull(OlinkID)metrics <- list( n_severe = sum(samples$Severity == "Severe"), n_non_severe = sum(samples$Severity == "Non-severe"), n_assays = nrow(detection), n_kept = length(kept_ids), n_sig_welch = nrow(welch_sig), n_sig_welch_up = sum(welch_sig$estimate > 0), n_sig_ols = sum(ordinary_fdr < 0.05), sum_welch_t = sum(welch$statistic), sum_ols_t = sum(ordinary_t))for (olink_id in top_ids) { row <- welch[welch$OlinkID == olink_id, ] metrics[[paste0("welch_t_", olink_id)]] <- row$statistic metrics[[paste0("welch_p_", olink_id)]] <- row$p.value metrics[[paste0("welch_fdr_", olink_id)]] <- row$Adjusted_pval metrics[[paste0("ols_coef_", olink_id)]] <- unname(fit$coefficients[olink_id, "severe"]) metrics[[paste0("ols_t_", olink_id)]] <- unname(ordinary_t[olink_id]) metrics[[paste0("ols_p_", olink_id)]] <- unname(ordinary_p[olink_id])}write_json(metrics, "outputs/olink_differential_metrics_r.json", auto_unbox = TRUE, digits = NA, pretty = TRUE)cat("wrote", length(metrics), "shared values\n")wrote 39 shared values# The best assay of each of the first five distinct proteins.top_ids = welch.drop_duplicates("Assay")["OlinkID"].head(5).tolist()welch_by_id = welch.set_index("OlinkID")ols_by_id = ols.set_index("OlinkID")metrics = { "n_severe": int(is_severe.sum()), "n_non_severe": int((~is_severe).sum()), "n_assays": len(detection), "n_kept": len(kept_ids), "n_sig_welch": len(welch_sig), "n_sig_welch_up": int((welch_sig["estimate"] > 0).sum()), "n_sig_ols": int((ols["fdr"] < 0.05).sum()), "sum_welch_t": float(welch["statistic"].sum()), "sum_ols_t": float(ols["t"].sum()),}for olink_id in top_ids: metrics[f"welch_t_{olink_id}"] = welch_by_id.loc[olink_id, "statistic"] metrics[f"welch_p_{olink_id}"] = welch_by_id.loc[olink_id, "p_value"] metrics[f"welch_fdr_{olink_id}"] = welch_by_id.loc[olink_id, "fdr"] metrics[f"ols_coef_{olink_id}"] = ols_by_id.loc[olink_id, "coef"] metrics[f"ols_t_{olink_id}"] = ols_by_id.loc[olink_id, "t"] metrics[f"ols_p_{olink_id}"] = ols_by_id.loc[olink_id, "p_value"]metrics = {key: float(value) for key, value in metrics.items()}with open("outputs/olink_differential_metrics_python.json", "w") as handle: json.dump(metrics, handle, indent=2)print("wrote", len(metrics), "shared values")wrote 39 shared valuesDays 3 and 7
Section titled “Days 3 and 7”Patients still in hospital gave more samples on days 3 and 7. These are repeated measures
of the same people, so a t-test on pooled samples would count one patient three times.
olink_lmer() fits a mixed model with a random intercept for each subject through
lmerTest, which is the route the paper took. The
block below runs it on the best assay of each of the top five proteins, with age group as a
covariate. Fitting the whole panel is the same call on the full long table.
# Days 0, 3 and 7 of the COVID-positive subjects. Day E samples are left out.npx_time <- npx_wide |> filter(Day %in% c("0", "3", "7")) |> mutate(subject = as.numeric(sub("_.*", "", `Public ID`)), Time = factor(paste0("D", Day))) |> select(SampleID = `Public ID`, subject, Time, all_of(top_ids)) |> pivot_longer(starts_with("OID"), names_to = "OlinkID", values_to = "NPX") |> inner_join(distinct(samples, subject, Severity, age_group), by = "subject") |> mutate(subject = factor(subject)) |> inner_join(select(assays, OlinkID, Assay, UniProt, Panel, Panel_Version), by = "OlinkID") |> mutate(PlateID = NA_character_, QC_Warning = NA_character_, Panel_Version = as.character(Panel_Version))
count(distinct(npx_time, SampleID, Time, Severity), Time, Severity)
lmer_fit <- olink_lmer(npx_time, variable = c("Severity", "Time"), random = "subject", covariates = "age_group", check_log = check_npx(npx_time))lmer_fit |> transmute(Assay, OlinkID, term, F = round(statistic, 1), p = signif(p.value, 3)) |> arrange(OlinkID, term) |> as.data.frame() |> print(row.names = FALSE)# A tibble: 6 × 3 Time Severity n <fct> <fct> <int>1 D0 Severe 1092 D0 Non-severe 1963 D3 Severe 914 D3 Non-severe 1245 D7 Severe 826 D7 Non-severe 57 Assay OlinkID term F p IL6 OID20101 Severity 181.1 2.34e-32 IL6 OID20101 Severity:Time 15.7 2.75e-07 IL6 OID20101 Time 13.4 2.20e-06 CHI3L1 OID20399 Severity 125.7 1.22e-24 CHI3L1 OID20399 Severity:Time 32.8 7.24e-14 CHI3L1 OID20399 Time 58.0 9.76e-23 PTX3 OID20570 Severity 138.8 3.31e-26 PTX3 OID20570 Severity:Time 7.5 6.22e-04 PTX3 OID20570 Time 44.1 5.97e-18 KRT19 OID20596 Severity 106.0 1.77e-21 KRT19 OID20596 Severity:Time 0.4 6.53e-01 KRT19 OID20596 Time 47.3 4.12e-19 TRIAP1 OID21403 Severity 120.0 1.14e-23 TRIAP1 OID21403 Severity:Time 2.9 5.48e-02 TRIAP1 OID21403 Time 1.8 1.67e-01The Severity:Time row asks whether the gap between the groups changes from day 0 to day
7. It does for CHI3L1, with F 32.8, and for IL6, with F 15.7. KRT19 keeps a stable gap, with
F 0.4 and p 0.653. The table shows raw p-values, because the adjustment that olink_lmer()
reports covers only these five assays.
Read the sample counts before the F-tests. 82 severe samples remain on day 7 against 57 non-severe ones, because discharged patients stop giving blood. That dropout follows the outcome, so each later day compares a different mix of patients, which the paper notes for day 3 as well.
How this step fails
Section titled “How this step fails”- Read the workbook without
na = "NA"and readxl turns the IFNG, GCG and MUC16 columns into text. pandas treats the textNAas missing by default. check_npx()stops on a missing plate or QC column. Fill those columns with NA. A made-upPasswould claim a QC result that the file does not hold.- Duplicated assays inflate the count. Report proteins as well as assays, or pick one assay per protein before you count.
- An unadjusted test mixes age into severity. Here it adds 195 significant assays that the age-adjusted model does not support.
The code for this page is in the companion repository under
guides/proteomics/olink-differential/.
Scientific references
Section titled “Scientific references”The OlinkAnalyze package by Nevola and colleagues supplies the functions for the analysis of Olink proteomic data.
Ritchie and colleagues, 2015 describe limma and its linear models for differential expression in microarray and RNA-seq data.
Further reading
Section titled “Further reading”The R t-test reference documents Welch’s unequal-variance calculation and the difference between paired and unpaired inputs. The limma linear model reference explains the design matrix used to include age alongside severity.
The R p-value adjustment reference describes BH adjustment. Read it when defining the assay family over which the reported false discovery rate is controlled.