简体   繁体   English

无法理解R中if条件中的错误消息

[英]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: 我的用R编写的程序有时(并非总是如此,但是当模拟运行很多次时几乎总是如此)会显示以下错误消息:

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. 现在,在该向量中最多显示一些值时,它会显示“值”,但出现错误消息时,其余值分别为0、0、0,...,0。 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: 该错误通常是由于NA值引起的:

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. 为了扩展@justin所说的内容,错误消息实际上是在告诉您它正在期待T / F,但没有收到。

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. 您的if( .... )语句中的括号。

In this specific case, looking at sum.wt1y1 == 0 | sum.wt2y2 == 0 在这种情况下,请查看sum.wt1y1 == 0 | sum.wt2y2 == 0 sum.wt1y1 == 0 | sum.wt2y2 == 0 would probably help you find the culprit. sum.wt1y1 == 0 | sum.wt2y2 == 0可能会帮助您找到罪魁祸首。

尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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