apply()

apply(X, MARGIN, FUN, ...)
Returns: matrix, array, or vector · Added in v1.0 · Updated March 13, 2026 · Base Functions
matrix iteration apply base loops

The apply() function is a base R function that applies a specified function to the margins (rows or columns) of an array or matrix. It provides a clean alternative to writing explicit for loops when working with matrix-style data structures.

Parameters

ParameterTypeDefaultDescription
Xarray/matrixRequiredAn array or matrix to apply the function over
MARGINinteger vectorRequiredA vector indicating which margins to apply over. Use 1 for rows, 2 for columns, or c(1, 2) for both
FUNfunctionRequiredThe function to apply to each margin
anyNoneAdditional arguments passed to FUN
simplifylogicalTRUEIf TRUE and the result is a scalar, attempts to simplify to a vector or matrix

Return Value

Returns a vector, matrix, or array depending on the value of MARGIN, the return type of FUN, and the simplify argument.

Basic Example

# Create a sample matrix
m <- matrix(1:9, nrow = 3, ncol = 3)
print(m)
#      [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5    8
# [3,]    3    6    9

# Apply sum over rows (MARGIN = 1)
row_sums <- apply(m, 1, sum)
print(row_sums)
# [1] 12 15 18

# Apply sum over columns (MARGIN = 2)
col_sums <- apply(m, 2, sum)
print(col_sums)
# [1]  6 15 24

Using Custom Functions

# Calculate row means
row_means <- apply(m, 1, function(x) mean(x))
print(row_means)
# [1] 4 5 6

# Apply a custom function with additional arguments
apply(m, 1, function(x, threshold) sum(x > threshold), threshold = 4)
# [1] 2 2 2

Working with MARGIN = c(1, 2)

# Apply a function to each element (returns a matrix)
apply(m, c(1, 2), function(x) x^2)
#      [,1] [,2] [,3]
# [1,]    1   16   49
# [2,]    4   25   64
# [3,]    9   36   81

Practical Example: Standardize Columns

# Standardize each column (mean = 0, sd = 1)
standardize <- function(x) (x - mean(x)) / sd(x)

m <- matrix(rnorm(30), nrow = 5, ncol = 6)
standardized_m <- apply(m, 2, standardize)
print(head(standardized_m))

When to Use apply()

apply() works best with matrices and arrays. For data frames, consider lapply() (returns a list) or sapply() (attempts to simplify). The MARGIN argument is what distinguishes apply() from other apply family functions.

Common Pitfalls

  1. Data frame coercion: apply() coerces data frames to matrices, which can fail with mixed types
  2. Simplification behavior: With simplify = TRUE, results may unexpectedly become a matrix instead of a list
  3. Margins > 2: For arrays with more dimensions, use MARGIN = c(1, 3) to apply over rows and third dimension simultaneously

See Also