Re-order the lines of code below to create a for
loop!
message(day)
days = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
}
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.
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
mean()
instead of the maximum valueNow, calculate the standard deviation (via sd()
) as well as the mean.
You should only have a single loop!
```r
means = numeric(ncol(dd))
sds = numeric(ncol(dd))
for (i in seq_along(dd)) { means[i] = mean(dd[[i]]) sds[i] = sd(dd[[i]]) } ```
Solutions are contained within this package:
vignette("solutions1", package = "jrProgramming")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.