Rnovice
Rnovice

Reputation: 119

How does one handle infinite values in matrices in R?

I have a matrix that I suspect has some infinite elements.

I have two questions:

  1. Is there an equivalent count function like the sum(is.na) which provides me with the number of infinites in the matrix?
  2. I would like to calculate the dot product of each row of my matrix with another vector. How do I disregard the infinite values? Something like na.rm = T function in the sum function.

Thank you

Upvotes: 0

Views: 570

Answers (1)

Marc in the box
Marc in the box

Reputation: 11995

Try this, but make sure your input data is of class matrix:

set.seed(1)

# make data
n <- 20
m <- 10
M <- matrix(rnorm(n*m), n, m)

# add Infs
M[sample(x = length(M), size = length(M)*0.1)] <- Inf
image(seq(n), seq(m), M, xlab = "rows", ylab = "columns")

# here is the vector that you want to multiply each row with
multVec <- seq(m)

# apply with removal of non-finite values
res <- apply(M, 1, function(x){
  tmp <- x * multVec
  sum(tmp[is.finite(tmp)])
})

Upvotes: 1

Related Questions