References

Some of the exercises in this document use the following references:

Loops

Exercise 1

Write a loop that iterates over the numbers 1 to 7 and prints the cube of each number using print().

for (i in c(1:7)){print(i^3)}

Exercise 2

Write a loop to simulate the flip of a coin twenty times, keeping track of the individual outcomes (1=head, 0=tails) in a vector that you preallocate.

coin<-vector(mode=“numeric”,length=20) #establish vector

for (i in 1:length(coin)) { #define loop iterations coin[i] <- rdiscrete (1, c(0.5, 0.5), c(0,1)) #‘flip’ and assign for each i } #close loop

print(coin) #making sure it worked

Exercise 3

Wrap the code in exercise 2 in a function called coinflip. The function accepts as argument a scalar, the number of flips and returns a vector with the results (1=head, 0=tails)

coinflip <- function(flips) {

coin<-vector(mode=“numeric”,length=flips) #establish vector for (i in 1:length(coin)) { #define loop iterations coin[i] <- rdiscrete (1, c(0.5, 0.5), c(0,1)) #‘flip’ and assign for each i } #close loop

return(coin) #storing results

} #close function

coinflip(7) #making sure it worked

Exercise 4

Repeat the coin flip 10 times for a sample of 100 in each round. Compute the fraction of heads in each round and save the result in a named vector, where the vector names are the rounds. Repeat the same exercise with a smple size of 10000. What happens to the fraction of heads as the number of draws grows?

f_coinflip <-function(flips, games) { #‘games’ is how many times to run the series of tosses

v <-vector(mode=“numeric”, length=games) #establishing games vector

for (j in 1:games) { #establishing outer loop

coin<-vector(mode=“numeric”,length=flips) #establish flips vector for (i in c(1:length(coin))) { #establish inner loop coin[i] <- rdiscrete (1, c(0.5, 0.5), c(0,1)) #‘flip’ and assign for each i } #close inner loop v[j] <- mean(coin) } #close outer loop

return(v) #storing results

} #closing function

f_coinflip(10,3) #making sure it worked

f_coinflip(100,10) #100 flips, 10 games f_coinflip(10000, 10) #10000 flips, 10 games #the fraction of heads approaches 0.5 as the sample size increases

Exercise 5

Use a nested loop (i.e. an outer loop that runs over rows with running variable \(i\) and an inner loop that runs over columns with running variable \(j\) (or vice versa)) that produces the following matrix

matrix<-matrix(,ncol=5,nrow=5) #defining matrix with NA

for (i in 1:nrow(matrix)) { #row loop for (j in 1:ncol(matrix)) { #column loop matrix[i,j] <- abs(i-j) } }

print(matrix) #making sure it worked