Write your own function (3)
Do you still remember the difference between an argument with and without default values? The usage section in the sd() documentation shows the following information:
sd(x, na.rm = FALSE)
This tells us that x has to be defined for the sd() function to be called correctly, however, na.rm already has a default value. Not specifying this argument won't cause an error.
You can define default argument values in your own R functions as well. You can use the following recipe to do so:
my_fun <- function(arg1, arg2 = val2) {
body
}
The editor on the right already includes an extended version of the pow_two() function from before. Can you finish it?
This exercise is part of the course
Intermediate R
Exercise instructions
- Add an optional argument, named
print_info, that isTRUEby default. - Wrap an
ifconstruct around theprint()function: this function should only be executed ifprint_infoisTRUE. - Feel free to experiment with the
pow_two()function you've just coded.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Finish the pow_two() function
pow_two <- function(x) {
y <- x ^ 2
print(paste(x, "to the power two equals", y))
return(y)
}