+4 votes
in Programming Languages by (17.0k points)
How can I find the indices of NaN in a vector and replace them with some other value (e.g. 0)?

Is there any R function that can be used?

1 Answer

0 votes
by (33.7k points)

To find the indices of NaN elements in a vector, you can use is.nan() method with which() method.

The below example shows how to find indices of NaN elements and how to replace them with 0.

> b<- c(11,12,13,1,34,15,34,54,21,51,87, NaN, 67, NaN, 101)
> b
 [1]  11  12  13   1  34  15  34  54  21  51  87 NaN  67 NaN 101
> which(is.nan(b) == TRUE)
[1] 12 14
> b[is.nan(b)] = 0
> b
 [1]  11  12  13   1  34  15  34  54  21  51  87   0  67   0 101
>

...