# Odds and ends and as always loops ...

The code we produced in class this week can be downloaded and reviewed here: Code-Day11.R and Code-Day12.R.

This week’s problem set can be found here:

We covered a number of less common control flow operators and a few odd functions but mostly discussed various loop structures and applications. See examples below:

#### all( ), any( ), and which( )

``````x <- -5:5

# Query if all elements of the vector x contain values smaller than 0

all(x < 0)

# Query if any elements of the vector x contain values smaller than 0

any(x < 0)

# Identify which elements of the vector x contain values smaller
# than 0

which(x < 0)
``````

#### counters

In the code below a counter is initiated at zero and then updated in the for-loop if an element of x is even.

``````x <- c(2, 5, 3, 9, 8, 11, 6)

count <- 0

for (i in 1:length(x)) {

if(x[i] %% 2 == 0)  {
count <- count + 1
}

}

count
``````

#### repeat-loop with the ‘break’ control flow operator

A repeat-loop will continue forever unless you specify a break.

``````x <- 1

repeat {
print(x)
x <- x + 1
if (x == 6) {
break
}
}
``````

#### for-loop with ‘next’ control flow operator

I forgot to mention this operator in class. Its usage and purpose is fairly straightforward. The next operator basically instructs R to skip to the beginning of the loop i.e., it is a temporary break.

``````for (i in 1:5) {
if (i == 3) {
next
}
print(i)
}
``````

#### while-loop with counter

The while loop repeats commands while some condition is met. As long as the condition is true the loop will continue. Make sure that the condition can be broken else the while-loop will continue, forever-ever.

``````count <- 0

while (count < 6) {
print(count)
count <- count + 1
}
``````