Creating Functions
Learn to define functions in R and the best practices for using them.
We'll cover the following...
Functions are an essential element of code organization. Without functions, our code quickly becomes a tangled mess of repeated lines and nested loops. But with them, we can reduce complexity, increase readability, and save valuable time by reusing code.
Like in other programming languages, we can define functions in R that take a set of inputs, process them, and return some outputs. Creating functions allows us to streamline our code by reducing repetitive sections and keeping our code modular, so we can easily recall steps that we’ve already coded. And the best part? We can create functions (and even packages!) to share with colleagues.
Let’s take a look at a code example of how to create functions in R:
-
Lines 15–21: Define a function called
calculate_avg_mpgwith two input arguments,IN_CarDataandIN_CarModel.- Lines 16–18: Calculate the output of the function by filtering the input dataset (
IN_CarData) for the car model passed inIN_CarModel, and then calculate the mean highway miles per gallon (mean(hwy)) for that car model in the dataset. - Line 20: Return the result of the calculation above as the result of the function.
- Lines 16–18: Calculate the output of the function by filtering the input dataset (
-
Line 24: Call the function, using
IN_MtCarsas the input dataset anda4as the car model to be measured. Save the result inOUT_AvgMpg_a4. -
Lines 28–34: Define a function very similar to the one defined above (lines 15–21), but now assign a default value to
IN_CarModel, which will be used in case the argument is left unspecified. -
Line 37: Call the function
calculate_avg_mpg_a4D...