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

Andrew Taylor
  • 3,438
  • 1
  • 26
  • 47
  • 4
    See here : http://stackoverflow.com/questions/18189753/rowsums-but-keeping-na-values (multiply by an `ifelse`) – etienne Nov 12 '15 at 13:11

2 Answers2

9

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.

Roland
  • 127,288
  • 10
  • 191
  • 288
0

not the best solution, but

a<-rowSums(df,na.rm=T)
a[a==0 & is.na(rowSums(df))]<-NA 

should work

zugabe
  • 54
  • 5