满足条件时中断循环,否则在 R 中重新运行

问题描述 投票:0回答:0

我在 R 中写了一个 for 循环 来检查输出是否满足某个条件。 如果满足条件,那么我需要打破循环并打印输出。 否则,循环需要运行直到满足条件。

我运行我的代码,但代码出错。我浪费了将近 3 个小时在这里和其他网站上寻找解决方案,但不知道我在哪里做错了。

这是一个可重现的代码

K= 13:19
sums0 = 3
a=NULL
sums1=sums0

for(i in length(K)) {
sums = 4+i   ## if this sum is less than the initial sums0/0.5 then I need to break the loop and print output as: sums0,sums,K[i]  ##
             ## otherwise, I need to recalculate the sum again for another i and check this new sums with the previous sums i.e., sum of i-1 iteration ##

sums1 = c(sums1, sums)

if(K[i]==K[1]) {a = ifelse(sums>(sums0)/0.5,paste(sums0,sums,K[i]),0)}  # for the first i #

if((K[i]>=K[2]) & (sums>sums1[i]/0.5)) {
next } 
print(c(sums1[i],sums,K[i]))
}

这给

Error in if ((K[i] >= K[2]) & (sums > sums1[i]/0.5)) { :  missing value where TRUE/FALSE needed
.

为什么会出现这个错误?非常感谢任何帮助。

r for-loop error-handling break next
© www.soinside.com 2019 - 2024. All rights reserved.