+4 votes
in Programming Languages by (40.5k points)

I am randomly generating elements of a vector which can be NaN. In the end, when I sum all elements of the vector, it returns NaN.

How can I exclude NaN from the vector so that the sum is not NaN?

Here is the issue:

> f <- c(0.0152, 0.023, 0.0907, 0.0082, 0.0121, 0.0819, 0.0218, 0.0386, NaN,  0.0073,  1e-04,  0.009,  0.0447,  0.0429,  0.0085)

> sum(f)

[1] NaN

1 Answer

+2 votes
by (56.8k points)
selected by
 
Best answer

You can use na.omit() routine to exclude NaN from the vector.

The following example shows how to use this routine:

> f <- c(0.0152, 0.023, 0.0907, 0.0082, 0.0121, 0.0819, 0.0218, 0.0386, NaN,  0.0073,  1e-04,  0.009,  0.0447,  0.0429,  0.0085)

> f <- na.omit(f)

> f

 [1] 0.0152 0.0230 0.0907 0.0082 0.0121 0.0819 0.0218 0.0386 0.0073 0.0001 0.0090 0.0447 0.0429 0.0085

attr(,"na.action")

[1] 9

attr(,"class")

[1] "omit"

> sum(f)

[1] 0.404

Related questions

+5 votes
1 answer
+5 votes
1 answer
+5 votes
1 answer

...