5

I have a matrix that looks like this

a = matrix(c(5,10,NaN,NaN,4,5,3,NaN,NaN,2), nr=5)
a

     [,1] [,2]
[1,]    5    5
[2,]   10    3
[3,]  NaN  NaN
[4,]  NaN  NaN
[5,]    4    2

Now I want to have those NaN's replaced by zeros. I know is.nan function will return the indices of those elements, but how can I make use of the fact that if a NaN exists in a row, then all elements of that row are all NaN's (as in the example above, rows 3 and 4). Thanks!

alittleboy
  • 10,616
  • 23
  • 67
  • 107

2 Answers2

22

I don't think there's any real need to make use of your knowledge about the rows, since replacing the NaN's is so easy anyway:

a[is.nan(a)] = 0

Output:

> a
     [,1] [,2]
[1,]    5    5
[2,]   10    3
[3,]    0    0
[4,]    0    0
[5,]    4    2

Doing it using your approach:

> a = matrix(c(5,10,NaN,NaN,4,5,3,NaN,NaN,2), nr=5)
> nan_rows = is.nan(a[, 1])
> nan_rows
[1] FALSE FALSE  TRUE  TRUE FALSE
> a[nan_rows, ] = 0
> a
     [,1] [,2]
[1,]    5    5
[2,]   10    3
[3,]    0    0
[4,]    0    0
[5,]    4    2
Marius
  • 58,213
  • 16
  • 107
  • 105
2

Try this, it works for me:

> a = matrix(c(5,10,NaN,NaN,4,5,3,NaN,NaN,2), nr=5)
> a[is.nan(a)] = 0
> a
     [,1] [,2]
[1,]    5    5
[2,]   10    3
[3,]    0    0
[4,]    0    0
[5,]    4    2
hd1
  • 33,938
  • 5
  • 80
  • 91