Functions are blocks of reusable code designed to perform a specific task. They help organize your code, make it modular, and easier to maintain.
The basic syntax for creating a function is:
function_name <- function(arg1, arg2, ...) {
# Code to execute
result <- arg1 + arg2 # example operation
return(result) # return the output
}
- function_name is the name you assign to your function.
- Inside the parentheses are arguments (inputs) your function accepts.
- The function body contains code that processes inputs.
- The return() statement outputs the final value.
add_numbers <- function(a, b) {
sum <- a + b
return(sum)
}
result <- add_numbers(5, 3)
print(result) # Output: 8
If you omit the return() statement, R returns the value of the last expression:
multiply <- function(x, y) {
x * y
}
print(multiply(4, 6)) # Output: 24
You can assign default values to arguments. If no value is passed, the default is used:
power <- function(base, exponent = 2) {
base ^ exponent
}
print(power(5)) # Output: 25 (5^2)
print(power(5, 3)) # Output: 125 (5^3)
circle_area <- function(radius) {
area <- pi * radius^2
cat("The area of the circle is:", area, "\n")
return(area)
}
result <- circle_area(3) # Prints message and returns area
To use a function, write its name followed by parentheses with any required arguments inside:
function_name(argument1, argument2, ...)
function() with arguments inside parentheses.return() to send back output (optional).Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!