简体   繁体   中英

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).

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) ...

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 sum.wt1y1 == 0 | sum.wt2y2 == 0 would probably help you find the culprit.

尝试这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM