4

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
  • 9,996
  • 22
  • 60
  • 105

2 Answers2

21

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
  • 54,802
  • 15
  • 100
  • 97
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
  • 32,598
  • 5
  • 75
  • 87