Defining Functions
A function consists of three main parts: the function name, the function arguments, and the function body. The function name is a label assigned to the function, which is used to call the function later. The function arguments are inputs that the function will use, and the function body contains the code that performs the operations using these inputs.
Syntax :
function_name <- function(arg1, arg2) {
# Function body
result <- arg1 + arg2
return(result)
}Where ,
- Function Name: The name you assign to the function, which is used to call it later.
- Arguments: The input values that the function accepts. These are specified within the parentheses.
- Function Body: Block of code that performs the task. It is enclosed in curly braces {}.
Here’s a simple example of defining and using a function in R using the provided syntax. This example creates a function that adds two numbers together:
# Define the function
add_numbers <- function(num1, num2) {
# Function body
result <- num1 + num2
return(result)
}
# Use the function
sum_result <- add_numbers(5, 10)
# Print the result
print(sum_result)
Output:
[1] 15
In this example we create a function that performs an addition of two numbers and returns the result. You can modify the function body to perform other operations or add more complexity as needed.
Build a function in R
Functions are key elements in R Programming Language allowing code to be packaged into reusable blocks. They simplify tasks by making code more modular, readable, and maintainable. So whether conducting data analysis, creating visualizations, or developing complex statistical models, understanding how to create and use functions in R is crucial.