Multiple arguments (1)
As you saw in the optional arguments example, functions can have multiple arguments. These can help extend the flexibility of your function. Let's see this in action.
pow <- function(x, power = 2) {
x^power
}
pow(2)
[1] 4
pow(2, power = 3)
[1] 8
Instead of a square()
function, we now have a version that works with any power.
The power
argument is optional and has a default value of 2
, but the user can easily change this. It is also an example of how you can add multiple arguments. Notice how the arguments are separated by a comma, and the default value is set using an equals sign.
Let's add some more functionality to percent_to_decimal()
that allows you to round the percentage to a certain number of digits.
This exercise is part of the course
Intermediate R for Finance
Exercise instructions
- Fill in the blanks in the improved
percent_to_decimal()
function to do the following:- Add a second optional argument named
digits
that defaults to2
. - In the body of the function, divide
percent
by 100 and assign this todecimal
. - Use the
round
function ondecimal
, and set the second argument todigits
to specify the number of decimal places.
- Add a second optional argument named
- Your function will work on vectors with length >1 too.
percents
has been defined for you. - Call
percent_to_decimal()
onpercents
. Do not specify any optional arguments. - Call
percent_to_decimal()
onpercents
again. Specifydigits = 4
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Percent to decimal function
percent_to_decimal <- function(percent, ___ = ___) {
___ <- percent / 100
___(decimal, ___)
}
# percents
percents <- c(25.88, 9.045, 6.23)
# percent_to_decimal() with default digits
___
# percent_to_decimal() with digits = 4
___