此代码产生错误:
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。但在这种情况下,我真的不知道错误是什么。
答案 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
已初始化为NA
而ppm[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)
}