Your first function
Time for your first function! This is a big step in an R programmer's journey. "Functions are a fundamental building block of R: to master many of the more advanced techniques … you need a solid foundation in how functions work." -Hadley Wickham
Here is the basic structure of a function:
func_name <- function(arguments) {
body
}
And here is an example:
square <- function(x) {
x^2
}
square(2)
[1] 4
Two things to remember from what Lore taught you are arguments and the function body. Arguments are user inputs that the function works on. They can be the data that the function manipulates, or options that affect the calculation. The body of the function is the code that actually performs the manipulation.
The value that a function returns is simply the last executed line of the function body. In the example, since x^2 is the last line of the body, that is what gets returned.
In the exercise, you will create your first function to turn a percentage into a decimal, a useful calculation in finance!
Cet exercice fait partie du cours
Intermediate R for Finance
Instructions
- Create a function named
percent_to_decimalthat takes 1 argument,percent, and returnspercentdivided by 100. - Call
percent_to_decimal()on the percentage6(we aren't using % here, but assume this is 6%). - A variable
pcthas been created for you. - Call
percent_to_decimal()onpct.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# Percent to decimal function
___
# Use percent_to_decimal() on 6
___
# Example percentage
pct <- 8
# Use percent_to_decimal() on pct
___