Lesson contents

R — Grouping data frames with missing values

Filter missing measurements before computing a grouped summary from a data frame.

A simple example

Total one group

  1. Start with A has 1 and 2
  2. Do this Group by A and sum
  3. Result 3
Both rows share the group A. Their values contribute to the same total.
Lesson.R
data <- data.frame(group = c("A", "A"), n = c(1, 2))
cat(tapply(data$n, data$group, sum)[["A"]])
Output
3
Advertisements

Calculate a mean per station

The logical index removes rows whose measurement is NA. aggregate groups the remaining values by station and computes each mean. A station with no observed values disappears after filtering.

East mean: 4. West mean: 8. Missing reading: Excluded.
Compare two measuring stations

An east station records 4 and a west station records 8. Group readings by station and leave missing observations out of each mean. A missing observation is a gap in the record, so giving it a value of zero would change the calculation.

Run the example

R 4. Run these commands from the directory containing the example.

Rscript Lesson.R
Lesson.R
readings <- data.frame(
  station = c("east", "east", "west"),
  value = c(4, NA, 8)
)
observed <- readings[!is.na(readings$value), ]
means <- aggregate(value ~ station, data = observed, FUN = mean)
for (i in seq_len(nrow(means))) {
  cat(sprintf("%s %g\n", means$station[i], means$value[i]))
}
Output
east 4
west 8

The east group has one observed value of 4. The west group has one value of 8. The missing observation contributes to neither mean.

Try it yourself

Add a measured value of 10 for east.

Check your answer

East now averages 7. West stays at 8. A missing value and a measured zero have different meanings.

An Introduction to R

Related tags

  • R
  • data frames
  • NA
  • aggregation