0

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 NAs?


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 NAs, but it should return NA if all row values are NAs.

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).

mat
  • 2,412
  • 5
  • 31
  • 69
  • 1
    well, set `na.rm` to `FALSE`, or am I missing something? – Maël Feb 14 '23 at 14:56
  • 1
    What you do is just like `sum(numeric(0))`. Summing nothing up to get a zero is reasonable for me. – Darren Tsai Feb 14 '23 at 14:57
  • 3
    Otherwise, `function(x) if(all(is.na(x))) NA_integer_ else sum(x, na.rm=TRUE)` – Maël Feb 14 '23 at 14:58
  • 1
    Partial dup: https://stackoverflow.com/questions/30371683/make-sum-of-an-empty-set-set-of-nas-na-instead-of-0 – Maël Feb 14 '23 at 14:58
  • 1
    Seems like an exact dupe? What's "partial" about it? – Ben Bolker Feb 14 '23 at 15:08
  • Because OP asking why on top of a possible solution, but yeah, that could be added as a duplicate – Maël Feb 14 '23 at 15:13
  • 1
    But "why" questions stray more towards "opinion-based". – Gregor Thomas Feb 14 '23 at 15:31
  • But quick comment answer: if you remove the `NA`s from a all-`NA` vector, what is left? Nothing. What is the sum of nothing? 0. Makes sense to me. Note that `sum(NULL)` is also 0 so this seems to be consistent. (Also documented in `?sum`: *"For historical reasons, `NULL` is accepted and treated as if it were `integer(0)`."*) – Gregor Thomas Feb 14 '23 at 15:32
  • Maybe use `replace` like: `M <- matrix(c(NA, NA, NA, 2), nrow = 2)` `replace(rowSums(M, na.rm = TRUE), rowSums(!is.na(M)) == 0, NA)` – GKi Feb 14 '23 at 15:36

0 Answers0