BudiBadu Logo
Samplebadu

R by Example: Functions

R 4.x

Defining reusable code blocks with this sample code demonstrating function creation with default parameters, variable argument lists using ellipsis, return value behavior, and anonymous function syntax for inline operations.

Code

# Defining a function
calculate_area <- function(length, width = 1) {
  area <- length * width
  return(area)
}

# Calling the function
a1 <- calculate_area(10, 5)   # 50
a2 <- calculate_area(10)      # 10 (uses default width)

# Function with variable arguments (...)
sum_squares <- function(...) {
  nums <- c(...)
  return(sum(nums^2))
}

res <- sum_squares(1, 2, 3, 4) # 1+4+9+16 = 30

# Anonymous function (lambda)
sapply(1:5, function(x) x^3)

Explanation

Functions in R are created using the function() directive and assigned to variables, making them first-class objects that can be passed as arguments to other functions and defined within other functions. Functions support default argument values specified in the parameter list, which are used when callers omit those arguments. The return value is either explicitly specified using return() or implicitly taken as the last evaluated expression in the function body.

The ellipsis ... argument allows functions to accept an arbitrary number of arguments, enabling flexible function signatures. This is commonly used to pass arguments down to other functions inside the body or to aggregate multiple inputs as shown in the sum_squares example. The ellipsis can be captured into a vector using c(...) or passed directly to other functions that accept variable arguments.

Anonymous functions are defined inline without assigning them to a variable, frequently used with the apply family of functions like lapply(), sapply(), and mapply(). These lambda-style functions provide concise syntax for one-off operations on data. R treats functions as first-class objects, allowing them to be stored in lists, returned from other functions, and manipulated like any other R object.

Code Breakdown

2
function(length, width = 1) defines parameters with default value for width.
4
return(area) explicitly returns value, last expression returned if omitted.
12
... ellipsis accepts arbitrary number of arguments for flexible signatures.
20
function(x) x^3 creates anonymous function for inline use with apply functions.