and we can replace the moving parts by our new column parameter.
Add the function body
Note
We don’t assign the output inside the function: the function merely makes the computation and we assign its output to our object when we call the function.
Notice how it is much easier to check whether we made a typo in this code.
Validate function parameters
We can pass wrong values to my_std()!
If we pass a column name that doesn’t exist in the data:
my_std("unknown_column")
Warning in mean.default(iris[[column]], na.rm = TRUE): argument is not numeric
or logical: returning NA
numeric(0)
No error, just a warning and a useless result!
we need to check user inputs
Validate function parameters
Step 1: list all input requirements.
the column should be a single value, e.g. my_std(c("Sepal.Length", "Petal.Width")) should fail;
the column should be a character value, e.g. my_std(1) should fail;
the column should exist in the data, e.g. my_std("column_1") should fail.
Validate function parameters
Step 2: check each of those.
my_std <-function(column) {if (length(column) !=1) {stop("The `column` parameter must be of length 1.") }if (!is.character(column)) {stop("The `column` parameter must be a character.") }if (!(column %in%names(iris))) {stop("Column '", column, "' doesn't exist in the data.") } (iris[[column]] -mean(iris[[column]], na.rm =TRUE)) /sd(iris[[column]], na.rm =TRUE)}
Validate function parameters
And now we have proper error messages!
my_std(c("Sepal.Length", "Petal.Width"))
Error in `my_std()`:
! The `column` parameter must be of length 1.
my_std(1)
Error in `my_std()`:
! The `column` parameter must be a character.
my_std("column_1")
Error in `my_std()`:
! Column 'column_1' doesn't exist in the data.
Validate function parameters
Packages for input checking
Several packages provide functions to check inputs and report useful error messages, e.g. rlang and checkmate (see also dreamerr, arg, chk, and more!).