In R programming, functions are a fundamental concept used to group together a set of statements to perform a specific task or computation. There are two main types of functions in R:
Built-in Functions (Base Functions):
These are functions that come pre-defined in R and are available for use without any additional installation or package loading. These functions are part of the base R package and cover a wide range of common data manipulation, statistical analysis, and other tasks. Here are some examples of built-in functions:
- mean(): Calculates the mean (average) of numeric values.
- sum(): Computes the sum of numeric values.
- length(): Returns the number of elements in a vector.
- str(): Displays the structure of an R object.
- plot(): Creates various types of plots.
- You can use these functions directly in your R code.
User-Defined Functions:
These are functions that you define yourself. User-defined functions are created to perform specific tasks or computations that are not covered by built-in functions, or to simplify complex code by encapsulating it in a function. To create a user-defined function in R, you typically use the function keyword. Here’s a basic structure of a user-defined function:
my_function <- function(argument1, argument2, …) {
# Function body with statements
# …
return(result)
}
- my_function is the name of your custom function.
- argument1, argument2, etc., are the function’s input parameters.
- The function body contains the code to execute when the function is called.
- return(result) specifies what the function should return as its output.
Example of a user-defined function:
add_numbers <- function(x, y) {
result <- x + y
return(result)
}
You can then call the user-defined function like this:
result <- add_numbers(5, 3)
This would set result to 8.
User-defined functions are essential for modularizing your code, making it more readable, and reusing code for specific tasks. You can also package user-defined functions into R scripts or R packages for better organization and sharing with others.