Question 1

Re-order the lines of code below to create a for loop!

  1. message(day)

  2. days = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")

  3. }

  4. for (day in days) {

days = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
for (day in days) {
  message(day)
}

\noindent Try changing day to i wherever day is seen. Does it change the output? Explain why

# The output will remain the same as the iterator, which acts as a placeholder for the
# iterator values in the vector, days, is being kept consistent throughout the body of the
# for loop.

Question 2

In the notes, we observed that it was straight forward to loop through a data set and select the maximum values:

library("tibble")
dd = tibble(x = rnorm(10),
            y = rnorm(10),
            z = rnorm(10))

max_cols = numeric(ncol(dd))

for (i in seq_along(dd)) {
  max_cols[i] = max(dd[[i]])
}
max_cols

Solutions

Solutions are contained within this package:

vignette("solutions1", package = "jrProgramming")


jr-packages/jrProgramming documentation built on Sept. 8, 2020, 9:35 p.m.