I would like to sum vectors that include NAs.
For example:
a <- c(5, 3, 1, NA, 2)
b <- c(NA, 1, 2, 1, 7)
The expected output would be:
[1] 5 4 3 1 9
sum
doesn't work in this situation, as sum(a, b, na.rm = T)
is equivalent to sum(c(a, b), na.rm = T)
.
+
does work (i.e. a + b
) but does not remove the NA
s.
You can use rowSums(cbind(a, b), na.rm = T)
, but in practice this can lead to messy code - for example if the vectors are columns of a data.table
.
Is there an equivalent of pmax
for sum, e.g. psum(a, b, na.rm = T)
?