Blain Waan
Blain Waan

Reputation: 443

Can't understand the error message in the if condition in R

My program written in R sometimes (not always, but almost always when the simulation is run for a large number of times) shows this error message:

Error in if (sum.wt1y1 == 0 | sum.wt2y2 == 0) zn[k] <- 0 else zn[k] <- (sum.wt1y1 *  : 
  missing value where TRUE/FALSE needed

Can anyone explain me what is the meaning of this error message? I cannot find where the error is. The final output is a vector. Now in that vector up to some values it shows "values" but the rest are 0, 0, 0,..., 0 when the error message appears. If the error message do not appear, then all the positions of the vector is filled up with values (no zeros).

Upvotes: 1

Views: 119

Answers (3)

Ricardo Saporta
Ricardo Saporta

Reputation: 55340

To expand on what @justin said, the error message is essentially telling you that it was expecting a T/F but did not get it.

When you see such an error, the best thing to do is to explore the value that is inside
the parens in your if( .... ) statement.

In this specific case, looking at sum.wt1y1 == 0 | sum.wt2y2 == 0 would probably help you find the culprit.

Upvotes: 1

IRTFM
IRTFM

Reputation: 263301

Try this:

which(is.na( sum.wt1y1 == 0 | sum.wt2y2 == 0))

Upvotes: 1

Justin
Justin

Reputation: 43245

The error arises due to NA values usually:

if (NA == 0) print('foo')

# Error in if (NA == 0) print("foo") : 
#   missing value where TRUE/FALSE needed

The solution is to remove missing values or include a check for them:

if (!is.na(x) & x == 0) ...

Upvotes: 8

Related Questions