In R, a function is like a recipe. You define a set of instructions for the computer to follow, and then you can use those instructions whenever you want without having to repeat yourself. Let's break it down with an example of a simple function that adds two numbers:
Example
# Define a function called add_numbers
add_numbers <- function(x, y) {
result <- x + y # Add the two numbers
return(result) # Return the result
}
# Now let's use the function
sum_result <- add_numbers(3, 5)
print(sum_result) # Output: 8
Here's what's happening:
add_numbers
using the function
keyword. Inside the parentheses ()
, we list the parameters x
and y
, which are the two numbers we want to add.x
and y
and store the result in a variable called result
.return()
statement to specify what the function should give back as its result, which in this case is the value stored in the result
variable.add_numbers
function with arguments 3
and 5
, it executes the instructions inside the function, adds 3
and 5
, and returns 8
.8
) is stored in the variable sum_result
, and then we print it.So, a function is a way to bundle up a set of instructions so that you can reuse them whenever needed, making your code more organized and efficient.