Question 1

fun4 = function(x) {
  if (x == 5) {
    y = 0
  } else {
    y = 1
  }
  return(y)
}

Change fun4() so that it:

Question 2

In practical 1, we calculated the mean of each column in a sample data frame using code similar to that below.

dd = data.frame(x = rnorm(10),
                y = rnorm(10),
                z = rnorm(10))
means = numeric(ncol(dd))
for (i in seq_along(dd)) {
  means[i] = mean(dd[, i])
}

The message() command provides us with an easier-to-use, more readable alternative to using print(). For instance,

x = 5
message("The value of x is ", x)
  1. Change the for loop such that it returns a warning message every time the mean goes above 0.3. The message should say "Warning, mean is greater than 0.3".

    r means = numeric(ncol(dd)) for (i in seq_along(dd)) { m = mean(dd[, i]) if (m > 0.3) { message("Warning, the mean is greater than 0.3") } means[i] = mean(dd[, i]) }

  2. Change the message such that it also tells us the column number of a large mean. For instance, if the mean of columns 2 was > 0.3, it would say "Warning, the mean of column 2 is greater than 0.3"

    r means = numeric(ncol(dd)) for (i in seq_along(dd)) { m = mean(dd[, i]) if (m > 0.3) { message("Warning, the mean of column ", i, " is greater than 0.3") } means[i] = mean(dd[, i]) }

  3. Convert the code into a function that takes two arguments, the data frame and the limit of the mean.

    r max_cols_limit = function(dd, lim) { means = numeric(ncol(dd)) for (i in seq_along(dd)) { m = mean(dd[, i]) if (m > lim) { message("Warning, the mean of column ", i, " is greater than ", lim) } means[i] = mean(dd[, i]) } return(means) } max_cols_limit(dd, 0.2)

Solutions

Solutions are contained within this package:

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


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