I am using a for loop to calculate values in a numeric vector. Sometimes the calculations result in NaN, as expected. I would like replace the NaN’s with zeros. Relevant parts of my code look like this:
NUM_CALCS <- 1000
FALSE_NEG <- vector("numeric", NUM_CALCS)
TRUE_POS <- vector("numeric", NUM_CALCS)
RECALL <- vector("numeric", NUM_CALCS)
for (i in 1:NUM_CALCS)
{
Calculate TRUE_POS[i] here
Calculate FALSE_NEG[i] here
RECALL[i] <- TRUE_POS[i] / (TRUE_POS[i] + FALSE_NEG[i])
RECALL[is.nan(RECALL[i])] <- 0
}
TRUE_POS[i]
and FALSE_NEG[i]
are only numeric values (including zero), as expected. When commenting out the is.nan() line and executing, RECALL contains some numeric values and some NaN’s, as expected. The problem is that at when the is.nan() line is included, at the end of the loop, RECALL contains only zeros. The non-zero numeric values have been replaced with zeros. If I execute RECALL[is.nan(RECALL)] <- 0
after the loop is completed, the NaN’s are replaced with zeros, but the numeric values remain, as desired. This solution would be fine, but due to subsequent calculations in the for loop, I require the NaN’s to be replaced at each iteration.