+5 votes
in Programming Languages by (71.8k 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

+1 vote
by (348k points)
selected by
 
Best answer

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
>

Related questions

+1 vote
1 answer
+4 votes
1 answer
+5 votes
1 answer
+5 votes
1 answer

...