I am having a problem with the rowSum function. What's happening is that any rows with NAs are being counted as 0 and I don't want that. Here is my data:
V1 V2 V3 V4
1 0 0 1
0 1 NA 1
NA NA NA NA
Here is what is happening:
V1 V2 V3 V4 SUM
1 0 0 1 2
0 1 NA 1 2
NA NA NA NA 0
I want this:
V1 V2 V3 V4 SUM
1 0 0 1 2
0 1 NA 1 2
NA NA NA NA NA
I've looked on several websites and I have tried so many different iterations of code and I keep getting the same thing. This is the most basic piece of code I have used, although I tried using dplyr. Can someone please help me?
df$sum <- rowSums(df, na.rm = T)
We can take advantage of the fact that
NA ^ 0
#[1] 1
NA ^ 1
#[1] NA
Using it in rowSums
, we can do:
rowSums(df, na.rm = TRUE) * NA^(rowSums(!is.na(df)) == 0)
#[1] 2 2 NA
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.