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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With