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
- Start with A has 1 and 2
- Do this Group by A and sum
- Result 3
data <- data.frame(group = c("A", "A"), n = c(1, 2))
cat(tapply(data$n, data$group, sum)[["A"]])
3
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.
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
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]))
}
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.