Skip to content

Missing Values

Real data has holes: a well fails QC, a probe drops out, a join leaves a gap. How you handle them changes the result, so it is worth doing on purpose rather than letting a function decide for you. This page uses expression_qc.csv, the same counts table with four measurements missing. R reads a blank as NA, Polars as null.

Every code block runs in a container in the companion repository, and the two languages agree on the counts and the imputed value.

Before anything else, see how many values are missing and where.

qc <- read.csv("../fixtures/expression_qc.csv")
sum(is.na(qc$counts))
qc |> filter(is.na(counts))
total missing counts: 4
sample_id condition gene counts
1 S02 control GAPDH NA
2 S03 control MYC NA
3 S06 treated EGFR NA
4 S08 treated BRCA1 NA

This example removes rows with a missing count. The four missing entries in the fixture leave 44 rows.

dropped <- qc |> drop_na(counts)
nrow(dropped) # 48 - 4 = 44
rows after drop: 44

Replace missing with a fixed value, for example 0. Convenient, but be careful: a zero count is a real claim about the biology, so filling counts with 0 is rarely correct.

filled <- qc |> mutate(counts = replace_na(counts, 0))
filled |> filter(sample_id == "S03", gene == "MYC")
sample_id condition gene counts
1 S03 control MYC 0

This example fills each gap with that gene’s mean across the samples with an observed count. It uses the same grouped pattern as a computed column. MYC’s missing value in S03 becomes the mean of its seven observed counts, about 540.7.

imputed <- qc |>
group_by(gene) |>
mutate(counts = ifelse(is.na(counts), mean(counts, na.rm = TRUE), counts)) |>
ungroup()
imputed |> filter(sample_id == "S03", gene == "MYC")
# A tibble: 1 × 4
sample_id condition gene counts
<chr> <chr> <chr> <dbl>
1 S03 control MYC 541.

The tibble rounds to 541 for display; both compute 540.714. This example demonstrates the syntax of a grouped replacement. It does not establish that a gene mean is an appropriate replacement for a missing count in differential expression.

Before you replace a measurement, investigate why it is absent and whether the analysis can use the remaining observations. The missing-data section explains mechanisms, uncertainty, and alternatives to a single replacement value.

The Polars missing data guide distinguishes null values from NaN values. It explains how null counts, row removal, and fill operations treat those representations. Use it to interpret the table operations shown here; the Missing Data lessons address the assumptions behind an imputation analysis.