Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: THEend8_
HW6: Wrap Up
Stat 33B
Introduction
The purpose of this assignment is to write some functions in R.
General Instructions
• Write your narrative and code in an Rmd (R markdown) file.
• Name this file as hw6-first-last.Rmd, where first and last are your first and last
names (e.g. hw6-gaston-sanchez.Rmd).
• Please do not use code chunk options such as: echo = FALSE, eval = FALSE, results
= 'hide'. All chunks must be visible and evaluated.
• Submit your Rmd and html files to Gradescope.
1) Toggling Switches
A room contains 100 toggle switches, originally all turned off. These switches can be initial-
ized in R with the following character vector switches:
num_switches <- 100
switches <- rep("off", num_switches)
100 people enter the room in turn. The first person toggles every switch, the second toggles
every second switch, the third every third switch, and so on, to the last person who toggles
the last switch only.
1.1) Toggling switches code (round 1)
Write R code to find out, at the end of this toggling process, which switches are turned on.
Strategy:
In order to solve this problem, we suggest that you start with a smaller vector of switches, for
instance: switches <- rep("off", 3). Workout the toggling process and see what hap-
pens. Then consider a larger vector: switches <- rep("off", 5) and follow the toggling
process. Once you get the right code, then generalize it to 100 switches.
1
1.2) Toggling switches code (round 2)
Use some of the recommendations given in labs 12 and 13—for improving the performance
of R code—in order to rewrite your code, and achieve better performance.
2) Number of steps in a Random Walk (in one dimension)
Consider a random walk of one particle in one dimension. This type of walk involves
taking a unit step with 0.5 probability to the right or to the left.
Write a function that measures how many steps it takes for one particle to reach a given
point x = xp. Your function should take the value of a given point, e.g. 10, and return the
number of steps to reach the provided point.
Report how many steps are needed to reach the points: x = 5, 50, 500, and 5000.
3) Random Walk in two space dimensions
Consider a discrete random walk in two dimensions. At each step there is a 0.25 probability
of moving one step to the left, right, up, or down. An example of a random walk of three
steps would be the first step is to move one unit to the right, the second step is to move one
unit up, and the third step is to move one unit back down to the position attained after the
first step.
3.1) Random Walk function
Write a function that generates such a random walk.
• The function should take two arguments:
– start: 2-length vector with the initial position; default start = c(0, 0)
– steps: positive integer for the number of steps to be taken.
• Your code should check that the input is a valid integer (it should handle zero and
negative numbers and non-integers gracefully).
• The output should be a list containing 3 elements:
– start: 2-length vector with the initial position
– final: 2-length vector with the final position
– path: a 2-column matrix with the full path of the walk; the columns correspond to
the x and y coordinates, respectively; and each row corresponds to the coordinates
at a given step
• Finally, you could use Rprof() to assess where the bulk of the computation is in your
code.
2
• If you are using for loops in your code, try re-implementing another function that
favors vectorized code.
Here’s an example for how to call a function that computes a random walk on two dimensions,
starting at position c(0, 0), and taking 7 steps.
set.seed(456)
random_walk2(start = c(0, 0), steps = 7)
## $start
## [1] 0 0
##
## $final
## [1] 2 1
##
## $path
## x_coords y_coords
## [1,] 0 0
## [2,] 1 0
## [3,] 2 0
## [4,] 2 1
## [5,] 1 1
## [6,] 2 1
## [7,] 2 0
## [8,] 2 1
3.2) Plot of Random Walk
a) Use your function for computing a random walk for position start = c(0,0), and
steps = 10, and plot the path of the walk. Graph the path using lines, and mark the
start and final positions with points of different colors.
b) Repeat (a) but this time for 100 steps.
c) Repeat (a) but this time for 1000 steps.
4) Probabilities
Consider the following situation. There are two boxes with balls of different colors:
• Box 1 contains two blue balls, and one red ball.
• Box 2 contains two blue balls, three red balls, and one white ball.
Consider a random experiment that consists of generating a random number that follows a
uniform distribution (min = 0, max = 1). If the number is greater than 0.5, then a sample
3
with replacement of size 4 is drawn from box 1. If the random number is less than or
equal to 0.5, then a sample without replacement of size is drawn from box 2.
The goal is to find the probability distribution for the number of blue balls. In other words:
• Probability of 0 blue balls
• Probability of 1 blue ball
• Probability of 2 blue balls
• Probability of 3 blue balls
• Probability of 4 blue balls
a) Create two character vectors box1 and box2 with colors of balls.
b) The random experiment involves generating a uniform random number using runif(1).
If this number is greater than 0.5, get a sample() with replacement of size = 4 from
box1. Otherwise, get a sample() without replacement of size = 4 from box2.
c) Repeat the experiment 1000 times using a for loop. To store the drawn samples, use
a matrix. This matrix will have 1000 rows and 4 columns. In each row you assign the
output of a random sample of balls. Your matrix could look like this (first five rows):
[,1] [,2] [,3] [,4]
[1,] "blue" "red" "red" "blue"
[2,] "red" "blue" "white" "red"
[3,] "red" "blue" "red" "red"
[4,] "red" "red" "red" "blue"
[5,] "red" "red" "blue" "white"
d) Once you filled the matrix with the drawn balls, compute the proportion of samples
containing: 0, 1, 2, 3, or 4 blue balls.
e) Plot the relative frequencies of number of blue balls over the series of repetitions. See
an example of this type of graph in the next page.