Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I replace a matrix element of NaN with 0 in R

Tags:

r

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!

like image 338
alittleboy Avatar asked Nov 29 '22 01:11

alittleboy


1 Answers

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
like image 144
Marius Avatar answered Dec 15 '22 11:12

Marius