0

This is part of my R code:

for (i in 1:n) {

...

Smw[i]<-(mw[i]-Emw[i])/(Vmw[i]^(0.5)

...

}

and I get this output

>Smw
 [1] 1.4205658 1.4357139 0.6331807 0.5006390 1.0186496 0.7762059 0.7129556 1.2702147 0.9721943
[10] 1.1156639 0.6908741 0.9994839 0.4976403 0.6265969 0.8362247 0.9150794 1.4028611 1.8190172
[19] 1.4290714 1.2475859 1.2874732 1.0358361 0.7494117 0.4077862 0.7082040 0.6408069 0.5158288
[28] 0.8990276 1.3660975 0.9901475 1.3291363 1.5966929 1.3004625 1.6013889 1.8312262 1.8797908
[37] 1.4265688 1.2947859 1.2763606 0.7276069 0.1641367 0.0000000 0.0000000 0.0000000 0.0000000
[46] 0.5363989 0.8374326 0.4455664 1.4205658       **NaN**

and I want to proceed the with

ooc=Cplus>5

lenOOC = sum(ooc)

lenOOC

I couldn't get the sum(ooc) since there is a NaN in my data. How can I convert the NaN to zero? My Smw data might contain negative values so max() is not suitable.

joran
  • 169,992
  • 32
  • 429
  • 468
OSS
  • 5
  • 2

1 Answers1

3

This is very simple to fix with a base R one liner using the is.na function to index the vector

Smw[is.na(Smw)] <- 0

This will make your summing work. However, it might be more appropriate to retain your NaN as this may be useful information later. Perhaps it is therefore better to use na.rm inside the sum function so that you are not irreversibly modifying information.

sum(Smw, na.rm = TRUE)

For example:

> x <- c(2, 8, NaN)
> sum(x)
NaN
> sum(x, na.rm = T)
10
> x
  2   8 NaN
rg255
  • 4,119
  • 3
  • 22
  • 40