Please submit this homework as an R Markdown (Rmd) file. See the introduction to Problem Set 1 if you need more information about the Rmd format.
Your file should use the following naming scheme
[last name]_ENS623_SP18_PS2.Rmd
For example,
Lammens_ENS623_SP18_PS2.Rmd
Problems 1 and 3 are each worth 10 points, Problem 2 is worth 5.
Write a function that uses a for
loop to calculate the mean of a vector of numbers.
Recall that the mean is:
\[ \bar{x} = \frac{\sum_{i=1}^n{x_i}}{n} \]
Compare the results of your function with that of the mean
function in base R.
while
loopswhile
loops are not necessarily as common as for
loops introduced in class Wednesday, but they are quite important. One key difference between for
loops and while
loops is that the former is usually set to repeat a given number of times, while the later repeats until some condition is met. Incidentally, this also means it’s easy to get into an infinite loop when writing while
loops. Be careful!
Here is a basic while
loop.
foo <- 0
while(foo < 10){
print(foo)
foo <- foo + 1
}
## [1] 0
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
Describe in words, what is happening in this loop.
Imagine you are flipping a fair coin (i.e., there is a 0.5 chance of getting a heads and a 0.5 chance of getting a tails). You want to continue flipping the coin until you get 100 heads. Write a script that simulates coin flips, and counts the number of times you need to flip the coin until you get 100 heads. Note that since the coin flip is a random process, it will not necessarily take you the same number of flips if you re-run the script.