Omit inf from row sum in R

Lcat91 picture Lcat91 · Mar 13, 2013 · Viewed 11.6k times · Source

So I am trying to sum the rows of a matrix, and there are inf's within it. How do I sum the row, omitting the inf's?

Answer

Joshua Ulrich picture Joshua Ulrich · Mar 13, 2013

Multiply your matrix by the result of is.finite(m) and call rowSums on the product with na.rm=TRUE. This works because Inf*0 is NaN.

m <- matrix(c(1:3,Inf,4,Inf,5:6),4,2)
rowSums(m*is.finite(m),na.rm=TRUE)