Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rowSums with all NA [duplicate]

Tags:

r

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?

like image 248
Andrew Taylor Avatar asked Sep 15 '25 14:09

Andrew Taylor


2 Answers

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.

like image 77
Roland Avatar answered Sep 17 '25 06:09

Roland


not the best solution, but

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

should work

like image 36
zugabe Avatar answered Sep 17 '25 05:09

zugabe