23 Functions
Functions are the vocabulary of R. They are pre-written scripts that perform specific tasks, saving you the effort of rewriting common procedures. Just like using the right word in a sentence, using the right function is key to an efficient and effective R program. Think of each function as a tool in your toolbox. The more tools you have and know how to use, the easier it will be to solve programming challenges. We have already mastered many functions for a variety of tasks. Now, our focus will shift to learning how to craft our own tools.
To create custom functions in R, follow this function structure:
For example,
Let us write a function that calculates the area of a rectangle. This function will require two arguments: the length and the width of the rectangle.
In this function named calculateArea, we have two parameters: length and width. We calculate the area by multiplying these two parameters and then return the result.
You can use this function by passing the length and width values as arguments: