Introduction

The main purpose of this lab is to practice control structures in R:

You 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.

Part 1: Vector and Control Structures

  1. (2 points) Write code that creates a vector 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).
#
  1. (2 points) Write code that replaces the observations in the vector 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.
#
  1. (2 points) Write 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.)
#

Part 2: Matrix and Control Structures

  1. (4 points) Create a \(100000\) by \(10\) matrix 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)
  1. (4 points) Another common loop structure that is used is the 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.
#

Part 3: Data Frame and Control Structures

  1. (4 points) Write a for loop to compute the mean of every column in mtcars and save the results to a vector col_mean. (Ignore missing values)
#
  1. (2 points) Compute the number of unique values in each column of iris and print the results during the loop.
#