The main purpose of this lab is to practice control structures in R:
if
and else
: testing a condition and
acting on itfor
: execute a loop a fixed number of timeswhile
: execute a loop while a condition is truerepeat
: execute an infinite loop (must break out of it
to stop)break
: break the execution of a loopnext
: skip an iteration of a loopYou will need to modify the code chunks so that the code works within
each of chunk (usually this means modifying anything in ALL CAPS). You
will also need to modify the code outside the code chunk. When you get
the desired result for each step, change Eval=F
to
Eval=T
and knit the document to HTML to make sure it works.
After you complete the lab, you should submit your HTML file of what you
have completed to Canvas before the deadline.
x
that
contains 100
random observations from the standard normal
distribution (this is the normal distribution with the mean equal to
0
and the variance equal to 1
).#
x
that are greater than or equal to 0
with a
string of characters "non-negative"
and the observations
that are smaller than 0
with a string of characters
"negative"
. Hint: try ifelse()
funtion.#
for
-Loop to count how many
observations in the vector x
are non-negative and how many
observations are negative. (There are many easier ways to solve this
problem. Please use for
-Loop to practice the things learned
in the lecture.)#
A
with the
numbers \(1:1000000\). Create a
for
-loop that calculates the sum for each row of the matrix
and save the results to a vector sum_row
. (Don’t print the
whole matrix in your submission as the matrix is very large. Otherwise,
you’ll lose scores for it.)#
Verify that your results are consistent with what you obtain with the
built-in rowSums
function.
sum_row_rowSums = as.integer(rowSums(A))
head(sum_row_rowSums)
while
loop, which functions much like a for
loop, but will only run as long as a test condition is
TRUE
. Modify your for
loop from exercise (a)
and make it into a while
loop. Write code to check if the
results from for
loop are the same as the results from
while
loop.#
for
loop to compute the mean of
every column in mtcars
and save the results to a vector
col_mean
. (Ignore missing values)#
iris
and print the results during the loop.#