Omit inf from row sum in R

后端 未结 5 2056
既然无缘
既然无缘 2020-12-15 18:07

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?

5条回答
  •  忘掉有多难
    2020-12-15 18:51

    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)
    

提交回复
热议问题