Omit inf from row sum in R

后端 未结 5 2042
既然无缘
既然无缘 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 19:05

    I'd use apply and is.infinite in order to avoid replacing Inf values by NA as in @Hemmo's answer.

    > set.seed(1)
    > Mat <- matrix(sample(c(1:5, Inf), 50, TRUE), ncol=5)
    > Mat # this is an example
          [,1] [,2] [,3] [,4] [,5]
     [1,]    2    2  Inf    3    5
     [2,]    3    2    2    4    4
     [3,]    4    5    4    3    5
     [4,]  Inf    3    1    2    4
     [5,]    2    5    2    5    4
     [6,]  Inf    3    3    5    5
     [7,]  Inf    5    1    5    1
     [8,]    4  Inf    3    1    3
     [9,]    4    3  Inf    5    5
    [10,]    1    5    3    3    5
    > apply(Mat, 1, function(x) sum(x[!is.infinite(x)]))
     [1] 12 15 21 10 18 16 12 11 17 17
    

提交回复
热议问题