繁体   English   中英

如何编写一个循环,直到满足条件为止

[英]How to write a loop that runs until a condition is satisfied

我已经在R中编写了以下循环。我希望循环一直运行,直到出现Y大于或等于3的情况为止。然后我想显示T,这是实验次数,直到出现这种结果为止。第一次。

T=0
while(Y<3)
{
  X=rbinom(1,5,0.5)
  Y=rbinom(1,X,0.5)
  Outcome=Y
  T=T+1
}
T 

我对R很陌生,我不确定如何更改已完成的工作以实现所需的功能。

您不需要为此的循环。 以下使用R的向量化,效率更高。

set.seed(42) #for reproducibility
n <- 1e4 #increase n and rerun if condition is never satisfied
X=rbinom(n,5,0.5) 
Y=rbinom(n,X,0.5)

#has condition been satisfied?
any(Y>3)
#TRUE

#first value that satisfies the condition
which.max(Y>3)
#[1] 141

您可以使用do直到构造:

while(TRUE){
  # Do things
  if(Y >= 3) break()
}

如果您不知道要执行多少次循环, 在这种情况下使用while循环。 它执行循环,直到满足您的期望条件为止。 您可以尝试以下代码。

T=0 #Index variable
Y=2 #Initial value that starts the while looping

首先, while循环检查此初始Y = 2,如果满足条件,则开始倾斜直到条件不满足。

while(Y<3) #Initialization of your looping
{
  X=rbinom(1,5,0.5)
  Y=rbinom(1,X,0.5)
  T=T+1
}
T 

while第一次检查其条件时,找不到Y。尝试将Y初始化为小于3的值。

Y <- 0

暂无
暂无

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

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