The basics of R functions

R is a programming language used in many areas of data analysis and statistics. And one of the most important concepts within R programming is R functions. These help make your code clear and modular.

What are R functions used for?

R functions are used to structure, organize and reuse code. They’re especially useful for performing complex analyses and large-scale data processing tasks as well as for creating custom analyses. There are many benefits to writing functions in R:

  • Abstraction: R functions let you encapsulate complex processes or calculations into a single, easy-to-understand interface. This makes code easier to maintain and read.
  • Reusability: R functions make it possible to execute a specific block of code repeatedly without having to rewrite it each time. This saves time and reduces susceptibility to errors.
  • Modularity: R functions let you break down a large project into smaller, manageable parts.

What is the syntax for R functions?

The syntax of functions in R is consistent and follows a clear pattern. A function in R consists of a few main components:

  • 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 represents the result of the calculation. 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 definition is introduced with the keyword function.

A function can also contain predefined 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 preinstalled?

R has an extensive collection of preinstalled 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 definition. Sometimes, functions like addition can also be performed by operators in R and replaced by the operator +.

Unless you’re just starting out in programming, you’ll probably be familiar with some of these predefined functions:

  • mean(): Calculates 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 characters of an R string to uppercase
  • sum(): Calculates the sum of numbers
  • print(): Outputs values on the console

Here’s an example of how to use the preinstalled 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 fundamental part of programming 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 accordingly.

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 predefined 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, calculating the absolute amount using the function will give you the correct result.

We use cookies on our website to provide you with the best possible user experience. By continuing to use our website or services, you agree to their use. More Information.