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)
?
You can try the following using mapply
to apply the sum function to the two vectors a and b. The na.rm=TRUE
instructs to remove NA values from the calculation:
a <- c(5, 3, 1, NA, 2)
b <- c(NA, 1, 2, 1, 7)
mapply(sum, a, b, na.rm=TRUE)
Output:
[1] 5 4 3 1 9
Or, you can opt to use reduce
as suggested by @Roland :
Reduce("+", lapply(list(a,b), function(x) replace(x, is.na(x), 0)))
mapply
is what you want:
mapply(sum, a, b, na.rm = TRUE)
# [1] 5 4 3 1 9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With