fun4 = function(x) { if (x == 5) { y = 0 } else { y = 1 } return(y) }
Change fun4()
so that it:
returns 0 if $x$ is zero.
r
fun4 = function(x) {
rtn_value = 0
if (x > 0) {
rtn_value = 1
} else if (x < 0) {
rtn_value = -1
}
return(rtn_value)
}
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)
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])
}
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])
}
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 are contained within this package:
vignette("solutions3", package = "jrProgramming")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.