Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Next in a Control Flow

Tags:

r

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 <- 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?

like image 576
Brandon Bertelsen Avatar asked Feb 14 '12 00:02

Brandon Bertelsen


People also ask

What does next do in a for loop?

next statement is an iterative, incremental loop statement used to repeat a sequence of statements for a specific number of occurrences. A for... next loop executes a set of statements for successive values of a variable until a limiting value is encountered.

What is control flow with example?

In computer programming, control flow or flow of control is the order function calls, instructions, and statements are executed or evaluated when a program is running. Many programming languages have what are called control flow statements, which determine what section of code is run in a program at any time.

What are the two types of control flow?

There are two primary tools of control flow: choices and loops. Choices, like if statements and switch() calls, allow you to run different code depending on the input. Loops, like for and while , allow you to repeatedly run code, typically with changing options.


2 Answers

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> 
like image 156
Dirk Eddelbuettel Avatar answered Oct 06 '22 02:10

Dirk Eddelbuettel


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 <- 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
like image 35
Josh O'Brien Avatar answered Oct 06 '22 00:10

Josh O'Brien