I was surprised to find out that sum(rep(NA, 3), na.rm = TRUE)
returns 0
instead of NA
. What is the logic behind this? Is there a way to force sum
-like functions to return NA
when all the inputs are NA
s?
Edit
As pointed out by @Maël, I could just use na.rm = FALSE
. The full story is I am applying sum
to the rows of a matrix with missing values and I would like it to return the row sum while ignoring NA
s, but it should return NA
if all row values are NA
s.
For instance, I would expect rowSums(matrix(c(NA, NA, NA, 2), nrow = 2), na.rm = TRUE)
to return c(NA, 2)
but it instead returns c(0, 2)
. And if na.rm = FALSE
, then it returns c(NA, NA)
.