此R代码产生缺失值,其中TRUE / FALSE错误

时间:2012-03-05 21:06:23

标签: r

此代码产生错误:

  

while(diff< limit){:缺少值为TRUE / FALSE时出错   需要

i <- 1
j <- 1
limit <- 0.05
diff <- 0
ppm <- rep(NA,20)
while(i[1]<=nrow(list)) 
{
  while(diff < limit) ##This is where the error is occurring
  {
    if(j==0)
       ppm <- rep(NA,length(ppm))
    ppm[j] <- list$ppm[i]      
    j <- j+1
    if(j > 1)
       diff <- ppm[j]-ppm[j-1]
  }
  print(ppm)
}

现在我发现这通常是因为while中的条件正在评估为NA,因此无法检查为TRUE / FALSE。但在这种情况下,我真的不知道错误是什么。

2 个答案:

答案 0 :(得分:3)

据我所知,ppm永远不会在while(){}内初始化,因为'j'永远不会== 0。我也看不到'i'在哪里递增。 (您可以考虑提供head(list$ppm)

我想我在这里可能是错的(因为你从未描述过目标),但也许你真正想要的是:

diff.ppm <- diff(list$ppm)
diff.ppm[1:which.min(diff.ppm >= limit)]

答案 1 :(得分:3)

第一次通过while循环:

  • j为1,ppm[1]设置为i
  • list$ppm(第一)元素
  • j增加到2
  • j现在是&gt; 1,因此,您ppm[2] 仍然是NA之间的区别,因为ppm已初始化为NAppm[2]尚未触及然而ppm[1];结果是NA

现在回到while循环的顶部,将diff(现在NA)与limit(固定为0.05)进行比较......繁荣。

i <- 1
j <- 1
limit <- 0.05
diff <- 0     ## diff() is a built-in, probably avoid ...
ppm <- rep(NA,20)
list <- data.frame(ppm=1:10)  ## list is a built-in, probably avoid ...
while(i[1]<=nrow(list))   ## why i[1] ??? why not just i ???
{
  while(diff < limit) ##This is where the error is occurring
  {
    if(j==0)  ## as DWin says: never true, j is initialized to 1
       ppm <- rep(NA,length(ppm))
    ppm[j] <- list$ppm[i]      
    j <- j+1
    if(j > 1) {  ## always true if j is initialized to 1 and incremented the first time
      diff <- ppm[j]-ppm[j-1]  ## will be NA if ppm[j-1] is NA
      cat(j,ppm[j-1],ppm[j],diff,"\n")  ## debugging statement!
     }
  }
  print(ppm)
}