df <- data.frame(a = c(1, 1, NA, 0, 1, 0),
b = c(0, 1, NA, NA, 0, 1),
c = c(NA, 0, NA, 0, 1, NA),
d = c(1, NA, NA, 1, 1, 0))
rowSums(df)
#[1] NA NA NA NA 3 NA
rowSums(df, na.rm=T)
#[1] 2 2 0 1 3 1
The first I get, but my assumption and hope was that the third observation would return NA
. Is there a way to get it to return NA for the third observation?
Here is one option:
rowSums(df, na.rm = TRUE) * NA ^ (rowSums(!is.na(df)) == 0)
# [1] 2 2 NA 1 3 1
This uses that anything ^ 0
equals 1 in R.
not the best solution, but
a<-rowSums(df,na.rm=T)
a[a==0 & is.na(rowSums(df))]<-NA
should work
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