user2980491 user2980491 - 1 year ago 90
R Question

Summing lots of Vectors; row-wise or elementwise, but ignoring NA values

I am trying to create a new vector that is the sum of 35 other vectors. The problem is that there are lots of NA values, but for this particular use, I want to treat those as zeros. Adding the vectors won't work, because if any of the 35 vectors contain an NA, the result is NA. Here is the example of the problem:

# [1] NA NA 7 NA

I want the result to be 1, 3, 7, 6.

I suppose I could create new versions of each of the vectors in which I replace the NA with a 0, but that would be a lot of work when applied to 35 vectors. Is there a simple function that will help me out?

42- 42-
Answer Source

Could also have used the rowSums function:

rowSums( cbind (col1,col2,col3), na.rm=TRUE)
#[1] 1 3 7 6

?rowSums   # also has colSums described on same help page
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download