Define Custom Functions in R

In Python, we define a function using the def reserved word followed by optional parameters in parenthesis. The body of the function is indented (very important!).

This defines the function but does not execute the body of the function.

In the below example, we define a new function called greet() which will print Hello Dolly when called.

def greet():
    print("Hello Dolly")

Once we have defined a function, we can call (or invoke) it as many times as we like.

greet()

Calling the function executes the function's body, in our case, it prints the text "Hello Dolly".

Hello Dolly

Function Arguments

Often a function will take its arguments, do some computation and return a value to be used as the value of the function call in the calling expression. The return keyword is used for this.

In the above example, we had a fixed output from the function ("Hello Dolly"). We can customize this using arguments. In the following revised code, we update the greeting based on the language specified at the time of calling the function:

def greet(lang):
    if lang == 'es':
        return 'Hola'
    elif lang == 'fr':
        return 'Bonjour'
    else:
        return 'Hello'

There are a few important things to notice here:

  • The function has one parameter lang. A parameter is a variable which we use in the function definition that is a "handle" that allows the code in the function to access the arguments for a particular function invocation.
  • We use the if condition to decide what the function should return depending on the argument supplied. If the argument passed is es, then the function will return Hola. If the argument is fr, then the function will return Bonjour and so on.
  • Notice that the function 'returns' a value not 'print' it, i.e., the value will be supplied back to the calling function and then the calling function can do whatever it wants with it.

Now that the function is defined, we can call it in the way we like:

print(greet('es'),"Dolly")
print(greet('fr'),"Dolly")
print(greet('en'),"Dolly")

These calls will output the following:

Hola Dolly
Bonjour Dolly
Hello Dolly

Multiple Arguments

A function can take multiple arguments. To do so, we define more than one parameter in the function definition. While calling the function, we simply add more arguments. The number and order of arguments and parameters must match. The following custom function calculates the area of a rectangle when its length and breadth are passed to it:

def rectangle_area(l,b):
    area = l*b
    return area

We can then call the function along with print to output the results.

print(rectangle_area(5,4))

This will print '20'.

While writing programs, you will often think about whether to convert a part of your code into a function or not. There are a few guiding principles to help you decide whether to create a function or not to.

  • Don't repeat yourself - make it work once and then reuse it
  • If something gets too long or complex, break up logical chunks and put those chunks in functions

Exercises

  • Make a function reverse_string that, given a string, returns that string in reverse.
  • Make a function that returns 'apples' if given a string, 'oranges' if given an integer, and 'bananas' if given anything else.

Data Science in Finance: 9-Book Bundle

Data Science in Finance Book Bundle

Master R and Python for financial data science with our comprehensive bundle of 9 ebooks.

What's Included:

  • Getting Started with R
  • R Programming for Data Science
  • Data Visualization with R
  • Financial Time Series Analysis with R
  • Quantitative Trading Strategies with R
  • Derivatives with R
  • Credit Risk Modelling With R
  • Python for Data Science
  • Machine Learning in Finance using Python

Each book includes PDFs, explanations, instructions, data files, and R code for all examples.

Get the Bundle for $29 (Regular $57)
JOIN 30,000 DATA PROFESSIONALS

Free Guides - Getting Started with R and Python

Enter your name and email address below and we will email you the guides for R programming and Python.

Data Science in Finance: 9-Book Bundle

Data Science in Finance Book Bundle

Master R and Python for financial data science with our comprehensive bundle of 9 ebooks.

What's Included:

  • Getting Started with R
  • R Programming for Data Science
  • Data Visualization with R
  • Financial Time Series Analysis with R
  • Quantitative Trading Strategies with R
  • Derivatives with R
  • Credit Risk Modelling With R
  • Python for Data Science
  • Machine Learning in Finance using Python

Each book comes with PDFs, detailed explanations, step-by-step instructions, data files, and complete downloadable R code for all examples.