Functions in R

DRS Training

R Functions

A function is a discrete section of code that carries out a particular routine task.

If you are duplicating sections of code to carry out similar actions in different parts of your script (or in multiple scripts) then you should definitely see about creating generally applicable functions.

The appropriate use of functions makes code more robust and efficient.

In a way the R language is really just a massive collection of functions!

Structure

The general structure of a function is:


Which is used/run as:

Defining a Function

Let’s define a function fahr_to_kelvin() that converts temperatures from Fahrenheit to Kelvin:


We define fahr_to_kelvin by assigning it to the output of function. The list of argument names are contained within brackets (), next the body of the function contains the statements that are executed when it runs, within curly braces {}.

It is useful to think of creating functions like writing a cookbook. First you define the “ingredients” that your function needs. In this case, we only need one ingredient to use our function: ‘temp’. After we list our ingredients, we then say what we will do with them, in this case, we are taking our ingredient and applying a set of mathematical operators to it and returning an output.

Task 1:

Copy the fahr_to_kelvin code into a script or the console and run it

try using the function to convert some \(^\circ\)F to \(^\circ\)Kelvin. e.g: fahr_to_kelvin(98)

change the function code to return values to 2 decimal places

hint

Note On running the code the function information is then listed under ‘functions’ in the Rstudio environment tab.

Task2

try creating a fahr_to_celsius function

Hint