A S*_*edo 104
非常自我解释.
repeat{
statements...
if(condition){
break
}
}
Run Code Online (Sandbox Code Playgroud)
或者像我想的那样.要获得do while循环的效果,只需在语句组的末尾检查您的条件.
42-*_*42- 24
请参阅?Control或R语言定义:
> y=0
> while(y <5){ print( y<-y+1) }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Run Code Online (Sandbox Code Playgroud)
因此do_while不存在作为R中的单独构造,但您可以伪造它:
repeat( { expressions}; if (! end_cond_expr ) {break} )
Run Code Online (Sandbox Code Playgroud)
如果您想要查看帮助页面,则无法键入?while或?repeat在控制台上,而是需要使用?'repeat'或?'while'.所有"控制结构"包含if在同一页面上,并且都需要在"?"之后引用字符.因此,解释器不会将它们视为不完整的代码,并为您提供继续"+".
小智 6
基于其他答案,我想分享一个使用while循环结构来实现do-while行为的示例.通过在while条件中使用一个简单的布尔变量(初始化为TRUE),然后在if语句中检查我们的实际条件.也可以在if语句中使用break关键字而不是continue < - FALSE(可能更高效).
df <- data.frame(X=c(), R=c())
x <- x0
continue <- TRUE
while(continue)
{
xi <- (11 * x) %% 16
df <- rbind(df, data.frame(X=x, R=xi))
x <- xi
if(xi == x0)
{
continue <- FALSE
}
}
Run Code Online (Sandbox Code Playgroud)