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.
Technical background: [1]. Practical recommendations below are VSPJ Consulting commentary.
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
References reviewed 21 September 2026. Sources support the technical background; workflow recommendations are independent implementation commentary. Release-watch details are dated snapshots. Check current documentation before adoption.
Have a related programming or implementation challenge?
Discuss it with Sai Prasad ↗