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.
Cet exercice fait partie du cours
Intermediate R for Finance
Instructions
- Fill in the blanks in the improved
percent_to_decimal()function to do the following:- Add a second optional argument named
digitsthat defaults to2. - In the body of the function, divide
percentby 100 and assign this todecimal. - Use the
roundfunction ondecimal, and set the second argument todigitsto specify the number of decimal places.
- Add a second optional argument named
- Your function will work on vectors with length >1 too.
percentshas been defined for you. - Call
percent_to_decimal()onpercents. Do not specify any optional arguments. - Call
percent_to_decimal()onpercentsagain. Specifydigits = 4.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de 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
___