Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Creating Functions in R

Introduction to Functions

Functions are fundamental building blocks in R programming that allow you to encapsulate code for reuse. They help to keep your code organized and make it easier to read and maintain. A function is defined using the function keyword followed by a set of parentheses containing parameters.

Defining a Function

To define a function in R, you use the following syntax:

my_function <- function(parameter1, parameter2) {
# Function body
return(value)
}

In the above syntax:

  • my_function is the name of the function.
  • parameter1 and parameter2 are the inputs to the function.
  • The body of the function contains the code that will be executed when the function is called.
  • The return() statement is used to specify the value that the function will return.

Example of a Simple Function

Let's create a simple function that adds two numbers:

add_numbers <- function(a, b) {
return(a + b)
}

To call this function and see the result:

add_numbers(5, 3)
[1] 8

Function with Default Parameters

Functions can also have default parameter values. This means if you do not provide a value for that parameter when calling the function, the default value will be used.

greet <- function(name = "Guest") {
return(paste("Hello,", name))
}

Now, if you call this function without any arguments:

greet()
[1] "Hello, Guest"

And if you provide a name:

greet("Alice")
[1] "Hello, Alice"

Returning Multiple Values

R allows functions to return multiple values as a list. This can be useful when you want to output several results from a single function call.

calculate_stats <- function(x) {
mean_value <- mean(x)
sd_value <- sd(x)
return(list(mean = mean_value, sd = sd_value))
}

To use this function:

calculate_stats(c(1, 2, 3, 4, 5))
$mean
[1] 3
$sd
[1] 1.581139

Conclusion

Creating functions in R is a powerful way to organize your code, make it reusable, and enhance its readability. By defining functions with parameters, default values, and the ability to return multiple values, you can write more efficient and structured code.