3

I have a matrix m in R , and I would like to remove -Inf values , and then calculate the colMeans of all columns. How can I do this in R?

m <- matrix(c(1, 3, 4, -Inf, 6, 7, 4, -Inf, 6, 0, 1, 3) , nrow = 3)
m
       [,1] [,2] [,3] [,4]
[1,]     1  -Inf    4    0
[2,]     3   6    -Inf   1
[3,]     4   7      6    3
Andrie
  • 176,377
  • 47
  • 447
  • 496
rose
  • 1,971
  • 7
  • 26
  • 32
  • 2
    Related: http://stackoverflow.com/questions/7518245/one-function-to-detect-nan-na-inf-inf-etc – Andrie Jun 04 '14 at 07:01

1 Answers1

19

Use is.finite. I presume this is how you wish to "remove" those -Inf values:

m[!is.finite(m)] <- NA
colMeans(m, na.rm=TRUE)
Hugh
  • 15,521
  • 12
  • 57
  • 100
  • 7
    We also have `is.infinite` at our disposal. Difference is trivial here - negating `is.finite` will select the same elements unless there are also `NaN` values. (But assigning to the smaller set of elements returned by `is.infinite` might be more efficient on huge matrices.) – jbaums Jun 04 '14 at 07:01