Get startedGet started for free

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!

This exercise is part of the course

Intermediate R for Finance

View Course

Exercise instructions

  • Create a function named percent_to_decimal that takes 1 argument, percent, and returns percent divided by 100.
  • Call percent_to_decimal() on the percentage 6 (we aren't using % here, but assume this is 6%).
  • A variable pct has been created for you.
  • Call percent_to_decimal() on pct.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Percent to decimal function
___



# Use percent_to_decimal() on 6
___

# Example percentage
pct <- 8

# Use percent_to_decimal() on pct
___
Edit and Run Code