Write a function with the name standardize
that normalizes the values of a given vector with the following formula:
\[(x - \bar{x}) / S\]
where \(x\) is each input value, \(\bar{x}\) is the sample mean value and \(S\) the sample standard deviation.base R
function for computing the standard deviation function is sd()
. Don’t forget to use the option na.rm = TRUE
and be careful when setting the brackets around the formula.
standardize <- function (x) {
(x - mean(x, na.rm = TRUE)) / sd(x, na.rm = TRUE)
}
As a preparation for the next task, please run the following code create a vector with 30 randomly selected values.
vector <- sample(1:100, 30)
standardize()
function to see if it works.
standardize(vector)
## [1] -0.44409780 -0.56822451 -0.65097566 1.74880749 -1.35436037 -0.98198023 -0.11309323 -1.18885809 -1.14748252 -0.85785351
## [11] -0.94060466 1.33505177 1.04542277 0.46616477 0.30066249 -1.27160923 -0.19584437 0.38341363 0.92129606 0.13516020
## [21] 1.62468077 0.71441820 -0.89922909 -1.02335580 0.83854491 1.37642734 1.91430977 -0.69235123 0.01103349 -0.48547337
<
) to check if a condition is true or false. For printing, you should use the print()
function.
if (standardize(vector)[1] < 0) {
print("TRUE")
} else {
print("FALSE")
}
## [1] "TRUE"