In class we explored basic loop structures.
Often the hardest task is not the computation, but controlling the data structure of outputing the loop. Try these variants:
- Create a for loop from 1:100 that sticks x * 2 into a list
- Create a for loop from 1:100 that sticks x * 2 into a vector
- Create a for loop from 1:100 that sticks x * 2 into a dataframe, with the first column as x.
- Create a for loop that skips odd rows in the dataframe using next, don’t cheat when using the seq statement iterator.
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"
- How many prime numbers are below 50?
- How many prime numbers are below 50, but above 10?
Now for the loops.
- Plot the number of prime numbers from 0 to 1000, by intervals of 100.
- Break the loop when the number of primes is greater than 100.