AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

R Functions: create functions in R

PARTAGEZ

R is a programming language used in many areas of data analysis and statistics. One of the main concepts in programming in R is functions. These help to manage the code in a clear and modular way.

Why do we use functions in R?

R functions are used to structure code, organize it, and reuse it. They are particularly useful when you are running complex analyzes or large data processing, or when you want to create custom analyses. Writing functions in R has many advantages:

  • Abstraction : functions in R offer the possibility of encapsulating complex processes or calculations in a single and understandable interface. The code is thus more easily maintained and read.
  • Reuse : R functions allow you to repeatedly execute a specific block of code without having to rewrite it each time. This saves time and reduces the risk of error.
  • Modularity : functions in R allow you to split a large project into small parts of a reasonable size.

Syntax of functions in R

The syntax of functions in R is consistent and follows a clear pattern. With R, a function consists of the following main components:

  • Function name : The function name normally indicates which task is executed.
  • Arguments : the arguments are the values ​​or variables which translate the function and which are processed by the function. A function can accept as many arguments as desired (or none). Furthermore, in R functions, default values ​​can be used for arguments.
  • Function body : The function body contains the code executed in the function and is indicated in curly brackets. This code can access and process arguments.
  • Return value : the majority of functions in R return using return() a value which constitutes the result of the calculation. This return value allows the function result to be used 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 name of the function, a And b are the arguments, the function body performs the addition and return(result) returns the result. It should also be noted that the definition of the R function is triggered by the keyword function.

A function can also contain predefined values ​​for arguments, which are used if no arguments are passed. The R function mentioned above would be the following with default values:

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

R

If the function is then called without specifying any arguments, it returns the value 3.

If you want to put your R project online, you can rent your own web hosting from IONOS so you have enough room for web projects of all types.

Pre-installed R functions

R has a huge collection of already installed functions, also called R commands, which can be used for various purposes. These functions are available and usable in R without prior definition. Functions, such as addition, can also be partially used with operators in R, in this case, the operator +.

If you're just starting to learn the basics of programming, check out some of the built-in functions from other programming languages ​​that you'll probably be familiar with:

  • mean() : calculates the average of the numbers
  • plot() : a plotting function in R for creating diagrams and graphs
  • read.csv() : lists the data in a CSV file
  • toupper() : transforms all characters in an R string into uppercase
  • sum() : calculates the sum of numbers
  • print() : returns the value to the console

Here is an example of using the preinstalled feature mean() in R. At the end of the code, the average of all numbers in the vector R is saved in the variable result.

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

R

Write your own R functions

There Creating your own functions in R is a fundamental part of programming in R. You can create functions specifically designed according to your requirements. You just need to stick to R syntax and think about what arguments you need in your function.

Here's a simple example of a custom R function that returns the absolute value of a number.

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

R

In this example, the function accepts an argument x. In the function body, the if statement in R checks if the number is negative (i.e. less than zero). If so, the function returns the negative value of x by multiplying by -1, which gives the absolute value of x. If x is already positive or zero, the function simply returns the value of x without modification.

Using functions in R

Once you have created a function, you can use it in your R code by calling the function name and specifying the required arguments. Using your own functions is similar to using predefined R functions.

Here is an example of using the function my_abs created above:

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

R

If you run this code example, you see that the number 5 appears on the screen. Calculating the absolute value using the function therefore returns the correct result.

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact