R is a pro­gram­ming language used in many areas of data analysis and stat­ist­ics. And one of the most important concepts within R pro­gram­ming is R functions. These help make your code clear and modular.

What are R functions used for?

R functions are used to structure, organise and reuse code. They’re es­pe­cially useful for per­form­ing complex analyses and large-scale data pro­cessing tasks as well as for creating custom analyses. There are many benefits to writing functions in R:

  • Ab­strac­tion: R functions let you en­cap­su­late complex processes or cal­cu­la­tions into a single, easy-to-un­der­stand interface. This makes code easier to maintain and read.
  • Re­usab­il­ity: R functions make it possible to execute a specific block of code re­peatedly without having to rewrite it each time. This saves time and reduces sus­cept­ib­il­ity to errors.
  • Mod­u­lar­ity: R functions let you break down a large project into smaller, man­age­able parts.

What is the syntax for R functions?

The syntax of functions in R is con­sist­ent and follows a clear pattern. A function in R consists of a few main com­pon­ents:

  • Function name: The name of the function, which usually indicates the task it performs.
  • Arguments: Arguments are values or variables passed to the function and processed by the function. A function can take any number of arguments (or none at all). In addition, R function default values can be used.
  • Function body: The function body contains the code that runs within the function and is enclosed in curly brackets. This code can access and process arguments.
  • Return value: Most functions in R use return() to return a value that rep­res­ents the result of the cal­cu­la­tion. This return value can be used in order to use the result of the function in other parts of the code.

Here’s a simple example of an R function that adds two numbers:

my_add <- function(a, b) {
    result <- a + b
    return(result)
}
R

In this example, my_add is the function name, a and b are the arguments, the function body does the addition, and return(result) returns the result. Also, the R function defin­i­tion is in­tro­duced with the keyword function.

A function can also contain pre­defined argument values, which are then resorted to when no arguments are passed. The above R function default values would look like this:

my_add <- function(a = 1, b = 2) {
    result <- a + b
    return(result)
}
R

If the function is now called without passing arguments, it returns a value of 3.

Tip

If you want to take your R project online, you can get webspace from IONOS, ensuring you have enough space for all your online projects.

What R functions come pre­in­stalled?

R has an extensive col­lec­tion of pre­in­stalled functions, also called R commands, which can be used for various purposes. These functions can be accessed and used in R without the need for prior defin­i­tion. Sometimes, functions like addition can also be performed by operators in R and replaced by the operator +.

Unless you’re just starting out in pro­gram­ming, you’ll probably be familiar with some of these pre­defined functions:

  • mean(): Cal­cu­lates the average of numbers
  • plot(): A plotting function in R for creating charts and graphs
  • read.csv(): Reads data from a CSV file
  • toupper(): Converts all char­ac­ters of an R string to uppercase
  • sum(): Cal­cu­lates the sum of numbers
  • print(): Outputs values on the console

Here’s an example of how to use the pre­in­stalled mean function in R. At the end of the code, the variable result contains the average of all numbers from the R vector numbers.

numbers <- c(2, 4, 6, 8, 10)
result <- mean(numbers)
R

Can I write my own R functions?

Creating your own R functions is a fun­da­ment­al part of pro­gram­ming in R, as you can create functions specific to your needs. All you have to do is look at the R syntax and consider what arguments your function needs.

A simple example of a custom R function that returns the amount of a number might look like this:

my_abs <- function(x) {
    if (x < 0) {
        return(-x)
    } else {
        return(x)
    }
}
R

In the example above, the function takes an argument x. In the function body, an R-if statement is then used to check whether it’s a negative or a positive number and the return value is adjusted ac­cord­ingly.

How to use your own R functions

Once you’ve created a function, you can use it in your R code by calling the function name and passing the necessary arguments. Using your own functions is similar to using pre­defined R functions.

Here’s an example using the my_abs function you just created:

result <- my_abs(-5)
print(result)
R

When you run the code sample, you’ll see that a 5 is output on the screen. So, cal­cu­lat­ing the absolute amount using the function will give you the correct result.

Go to Main Menu