在控制流中使用Next

时间:2023-02-02 20:23:00

There doesn't seem to be any examples of 'next' usage in the control flow help page. I'd like it to skip to the next iteration based on a condition within the script.

在控制流帮助页面中似乎没有任何“下一次”用法的示例。我希望它根据脚本中的条件跳到下一个迭代。

Using the example below, let's say I don't want it to print, unless x[i] > 5, the expected output would be 5 through 10 on screen:

使用下面的例子,假设我不想打印,除非x [i]> 5,预期的输出在屏幕上是5到10:

x <- 1:100
for(i in 1:10) {
# next(x[i] < 5) # Just for conceptualizing my question.
print(x[i])
}

How would I go about implementing the use of next to accomplish something like what's shown above?

我将如何实现使用next来完成上面显示的内容?

2 个解决方案

#1


13  

I will give you a complete example and a 'yes' but I am unsure what your questions is:

我会给你一个完整的例子和'是',但我不确定你的问题是什么:

R> for (i in 1:10) {
+     if (i < 5) next
+     print(i)
+ }
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
R> 

#2


9  

To make this work, you need to test whether x < 5 and, if it is, go to next. next will, in turn (to quote the help page), "[halt] the processing of the current iteration and [advance] the looping index", starting back through the loop again.

要使其工作,您需要测试x <5,如果是,则转到下一个。接下来将(引用帮助页面),“[暂停]当前迭代的处理和[提前]循环索引”,再次从循环开始。

x <- 1:100
for(i in 1:10) {
    if(x[i] < 5) next
    print(x[i])
}
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

#1


13  

I will give you a complete example and a 'yes' but I am unsure what your questions is:

我会给你一个完整的例子和'是',但我不确定你的问题是什么:

R> for (i in 1:10) {
+     if (i < 5) next
+     print(i)
+ }
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
R> 

#2


9  

To make this work, you need to test whether x < 5 and, if it is, go to next. next will, in turn (to quote the help page), "[halt] the processing of the current iteration and [advance] the looping index", starting back through the loop again.

要使其工作,您需要测试x <5,如果是,则转到下一个。接下来将(引用帮助页面),“[暂停]当前迭代的处理和[提前]循环索引”,再次从循环开始。

x <- 1:100
for(i in 1:10) {
    if(x[i] < 5) next
    print(x[i])
}
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10