
Programming in R can be a very beneficial skill for people interested in or already working in statistics, data analytics, and visualization of various kinds of datasets. The R programming language is vastly used across various domains and has remained relevant ever since its invention.
Knowing how to write and use modular code through functions is very important when coding in R and many other programming languages. This enables you to reuse your code without having to repeat the same set of instructions over and over.
In this tutorial, you will learn how to write and use functions in the R programming language efficiently.
Objectives
By going through this tutorial you will be able to:
- Understand the importance and real-life uses of the R programming language
- Know what functions are and how to create them
- Importance of using functions while programming in R
What is the R Programming Language
R is a free and open-source programming language (meaning it is available to everyone for use) and can also be considered as an environment for statistical computing and graphics. It was first written by Ross Ihaka and Robert Gentleman (alias R&R) of the University of Auckland’s Statistics Department; meanwhile, the R programming language that is in use today is a joint effort of various global contributions and it is managed by a team called the R Core Team. Find more information here at the r-project.
Knowing how to program in R is an invaluable skill in the Data Science Industry as its application cuts across Machine Learning, Web Scraping, and AI art to mention but a few.
The R programming language has so many real-life applications—as it has been used by professionals over the years to craft solutions that are being used even to this day. Given below are some of the applications of R:
- Data Analysis: R is considered one of the most-used tools for statisticians and data scientists working with complex datasets. It has built-in statistical functions and packages that make it easy to analyze data, find trends, and make predictions
- Data Visualization: R makes data visualization easy due to the availability of mature, tested and trusted libraries like ggplot2 and plotly, R is highly effective for creating graphs and visualizations that help convey insights understandably
- Statistical Modeling: Statistics is at the core of R’s design and creation, making it highly useful and efficient for building and testing statistical models. Researchers, economists, and social scientists have been using R for numerous tasks, including hypothesis testing, regression analysis, and simulation
- Bioinformatics: In recent times, R has become a key tool in bioinformatics, where it helps biologists analyze genetic data, run statistical tests, and visualize complex datasets in genomics and proteomics
- Finance: Analysts and financial companies use R for tasks like risk analysis, portfolio management, and time series analysis. R’s robust statistical capabilities make it valuable for modeling financial data
- Marketing and Business Intelligence: R helps marketing teams analyze customer data, segment audiences, and measure campaign performance. It’s often used for A/B testing and other experiments
- Social Science Research: R is popular in social sciences for survey analysis, experimental data, and demographic studies. It’s also widely used in academia because it strongly supports statistical techniques
What are Functions?
A function can be conceptualized as a block or collection of several lines of code that is tailored to solving a specific task. Functions provide modularity; by helping you organize your code and prevent repetition. Whenever you’re faced with a similar problem as what the function was designed to solve, you can simply reuse the function to solve the problem without having to write all the lines of code again.
Knowing how to create and use functions cannot be overstated; it ensures readability, code organization, and reusability.
Anatomy of a Function in R
Functions in R are typically written as shown in the snippet below.
function_name <- function(arg1, arg2, ...) {
# This is the body of your function:
# It is where you write the code that performs the desired operations
return(output) # the return statement
}
Explanation of each part:
- function_name: This is the name you assign to the function, which allows you to call it later. In R, the function name is usually assigned with the <- operator.
- function The function keyword tells R that you’re defining a function. It is followed by parentheses containing the function’s arguments (inputs).
- (arg1, arg2, …) These are the parameters or inputs that the function takes. They go inside the parentheses after a function. Arguments allow the function to accept different values each time it’s called.
- Function Body This is where the code to perform the function’s task goes. It’s placed inside curly braces {}. The function body can include calculations, conditional statements, loops, and other R functions.
- Return Statement (return(output)) The return function specifies what value the function should output when it’s called.In R, if you don’t include return, the last evaluated expression in the function body is automatically returned.
Step-by-Step Guide to Creating a Function in R
- Identify and break down the problem or task you intend to solve logically
- Identify the algorithm or steps that can efficiently solve the task
- Write pseudo code (This refers to your approach to solving the task, stating the procedures you will follow to arrive at your solution using the earlier selected algorithm in a structured way. The pseudo-code is not bound to any programming language, syntax, or rules) for the task using plain English or whatever language you are conversant with
- Code and run the solution in R and test
Example Function
The code snippet below shows an example of a simple function called add_numbers that adds two numbers using R:
Let’s define a function named add_numbers that takes two arguments, multiplies them, and returns the result.
add_numbers <- function(num1, num2)
{ # Function name and arguments
sum <- num1 + num2
# Function body: add the inputs
return(sum) # Return the result
}
Now let’s use the add_function we earlier created to add two numbers; by calling, as shown below
result <- add_numbers(4, 5) print(result) # Output: 9
Example breakdown:
- Function Name: add_numbers is the name of the function
- Arguments: The function accepts two arguments, num1 and num2
- Function Body: Inside the body, num1 and num2 are added and stored in sum
- Return Statement: return(sum) specifies that the result of num1 + num2 should be returned
Whenever we want to add two numbers to our program, we can always call the add_numbers function, and we have our answer instead of writing the lines of code all over again to perform the same task; this way, we keep our close base cleaner. Just imagine you had a bigger function that computes rather more complex data than what we have in the example above; you can now see that you will save yourself a lot of stress by modularising your code in functions.
Conclusion
Functions in R are very important and are always used by professionals to ensure that code is readable and reusable, just as shown in the snippets above. R functions are structured with a name, arguments, a function body, and an optional return statement to output the result. This simple structure makes functions in R easy to define and flexible to use in many different contexts.
