Odds and ends ...

The code we produced in class this week can be downloaded and reviewed here: Code-Day13.R and Code-Day14.R. The prompt for Assignment 1 can be found here: Assignment1.pdf.

We covered a number of less common control flow operators and a few odd functions. 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

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 command 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.

count <- 1

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