An empty contribution is not necessarily a measured zero
In R, sum(x, na.rm = TRUE) returns zero when all values are missing. That may be correct for one task and misleading for another. Decide the intended rule before summarising. Show the number observed alongside the summary.
Make the rule visible
An explicit all-missing branch makes the assumption reviewable. Test numeric vectors containing only NA, a mixture of NA and numbers, zeros and an empty vector. Agree whether an empty vector and an all-missing group should have the same output.
Illustrative example
safe_sum <- function(x) {
if (length(x) == 0L || all(is.na(x))) return(NA_real_)
sum(x, na.rm = TRUE)
}
Review and test this example against your own inputs and specification before use.
Sources & further reading
Sources checked 20 September 2026. Implementation commentary reflects a practical review perspective; source material may change.
Have a related programming or implementation challenge?
Discuss it with Sai ↗