LoslegenKostenlos loslegen

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.

Diese Übung ist Teil des Kurses

Intermediate R for Finance

Kurs anzeigen

Anleitung zur Übung

  • Fill in the blanks in the improved percent_to_decimal() function to do the following:
    • Add a second optional argument named digits that defaults to 2.
    • In the body of the function, divide percent by 100 and assign this to decimal.
    • Use the round function on decimal, and set the second argument to digits to specify the number of decimal places.
  • Your function will work on vectors with length >1 too. percents has been defined for you.
  • Call percent_to_decimal() on percents. Do not specify any optional arguments.
  • Call percent_to_decimal() on percents again. Specify digits = 4.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

# 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
___
Code bearbeiten und ausführen