Omit inf from row sum in R

后端 未结 5 2044
既然无缘
既然无缘 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:46

    Try this...

    m <- c( 1 ,2 , 3 , Inf , 4 , Inf ,5 )
    sum(m[!is.infinite(m)])
    

    Or

    m <- matrix( sample( c(1:10 , Inf) , 100 , rep = TRUE ) , nrow = 10 )
    sums <- apply( m , 1 , FUN = function(x){ sum(x[!is.infinite(x)])})
    
    > m
          [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
     [1,]    8    9    7  Inf    9    2    2    6    1   Inf
     [2,]    8    7    4    5    9    5    8    4    7    10
     [3,]    7    9    3    4    7    3    3    6    9     4
     [4,]    7  Inf    2    6    4    8    3    1    9     9
     [5,]    4  Inf    7    5    9    5    3    5    9     9
     [6,]    7    3    7  Inf    7    3    7    3    7     1
     [7,]    5    7    2    1  Inf    1    9    8    1     5
     [8,]    4  Inf   10  Inf    8   10    4    9    7     2
     [9,]   10    7    9    7    2  Inf    4  Inf    4     6
    [10,]    9    4    6    3    9    6    6    5    1     8
    
    > sums
     [1] 44 67 55 49 56 45 39 54 49 57
    

提交回复
热议问题