Worksheet 4 - Loops and Flow Statements

In class we explored basic loop structures.

Loops and Outputs

Often the hardest task is not the computation, but controlling the data structure of outputing the loop. Try these variants:

  1. Create a for loop from 1:100 that sticks x * 2 into a list
  2. Create a for loop from 1:100 that sticks x * 2 into a vector
  3. Create a for loop from 1:100 that sticks x * 2 into a dataframe, with the first column as x.
  4. Create a for loop that skips odd rows in the dataframe using next, don’t cheat when using the seq statement iterator.

Using user defined functions within a loop.

We’ll be getting into user-defined functions in the next section, so here is a preview to the topic.

This is a generic function for finding prime numbers,

http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

The function is a bit slow, so don’t go too high!

sieve <- function(n) {
    n <- as.integer(n)
    if (n > 1e+06) 
        stop("n too large")
    primes <- rep(TRUE, n)
    primes[1] <- FALSE
    last.prime <- 2L
    for (i in last.prime:floor(sqrt(n))) {
        primes[seq.int(2L * last.prime, n, last.prime)] <- FALSE
        last.prime <- last.prime + min(which(primes[(last.prime + 1):n]))
    }
    which(primes)
}

# Test
paste(sieve(10), "is prime")
## [1] "2 is prime" "3 is prime" "5 is prime" "7 is prime"
  1. How many prime numbers are below 50?
  2. How many prime numbers are below 50, but above 10?

Now for the loops.

  1. Plot the number of prime numbers from 0 to 1000, by intervals of 100.
  2. Break the loop when the number of primes is greater than 100.