Functions in R provide a mechanism to group together a set of operations and then use them as a single unit. When creating functions, it's common to have them perform operations on specific values or datasets, which are passed into the function as arguments.
Structure of Functions with Multiple Arguments
function_name <- function(arg1, arg2, ..., argN){ # Function body # Computation using the arguments return(value)
}
Where arg1, arg2, ..., argN are the different arguments the function accepts.
Examples of Functions with Multiple Arguments
A simple function to add two numbers
add_numbers <- function(x, y) { return(x + y)
}
print(add_numbers(3, 5)) # Outputs: 8
A function to calculate the area of a rectangle
rectangle_area <- function(length, width) { return(length * width)
}
print(rectangle_area(10, 5)) # Outputs: 50
A function to raise a number to a given power
raise_power <- function(base, exponent) { return(base^exponent)
}
print(raise_power(2, 3)) # Outputs: 8
Using Default Values for Arguments
R allows setting default values for function arguments. This is handy when you want your function to have optional parameters.
raise_power_default <- function(base, exponent = 2) { return(base^exponent)
}
print(raise_power_default(4)) # Outputs: 16, uses the default exponent of 2
print(raise_power_default(4, 3)) # Outputs: 64
Using Ellipsis (...) for Flexible Arguments
In R, if you're unsure about the number of arguments or want to accept a varying number of arguments, you can use the ellipsis (...). The ellipsis is often used when extending other functions or methods and when the number of arguments cannot be predetermined.
print_numbers <- function(...) { nums <- list(...) for (num in nums) { print(num) }
}
print_numbers(1, 2, 3, 4) # Outputs each number on a new line
Named Arguments
When calling a function with multiple arguments, you can specify them by name, rather than just by their position. This can make your code clearer, especially if a function has many optional arguments.
rectangle_area(length = 15, width = 10) # Outputs: 150
rectangle_area(width = 10, length = 15) # Outputs: 150, order doesn't ma