R apply() Function for Matrix Rows, Columns, and Elements
In R, the apply() function applies a function across the rows, columns, or both dimensions of a matrix. For a matrix, use MARGIN = 1 for rows, MARGIN = 2 for columns, and MARGIN = c(1, 2) when the function must be evaluated for every individual matrix element.
For simple element-wise arithmetic, such as adding a number or taking a square root, direct vectorized operations are usually clearer and faster. The examples below show both approaches.
Syntax of apply() for an R Matrix
The syntax of apply() function in R is
apply(X, MARGIN, FUN, ...)
The arguments are:
Xis the matrix or array to process.MARGINspecifies the dimensions over whichFUNis applied. For a matrix,1selects rows,2selects columns, andc(1, 2)selects individual row-column positions.FUNis the function to apply....contains additional arguments passed toFUN.
How MARGIN Changes apply() Matrix Processing
The function receives different input depending on the value of MARGIN:
MARGIN | Input passed to the function | Typical use |
|---|---|---|
1 | One complete row at a time | Row sums, row means, or row-wise custom calculations |
2 | One complete column at a time | Column sums, column means, or column-wise transformations |
c(1, 2) | One matrix element at a time | Applying a scalar function to every cell |
A function such as function(x) x + 2 is vectorized, so it can transform a complete row or column and still produce an element-wise-looking result. However, apply(M, 2, FUN) technically calls FUN once per column, not once per element.
Apply a Function to Every Value by Processing Matrix Columns
In this example, we will take a 2D matrix. Write a function to increment the argument by 2. Then apply the function on all elements of the matrix.
Because MARGIN = 2, incrementBy2 receives one column at a time. Addition is vectorized in R, so every value in each column is increased by 2.
example.R
M = matrix(c(1:12), ncol=3)
incrementBy2 <- function(x) {
return(x+2)
}
y = apply(M, 2, incrementBy2)
Output
> print(M)
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
> print(y)
[,1] [,2] [,3]
[1,] 3 7 11
[2,] 4 8 12
[3,] 5 9 13
[4,] 6 10 14
Apply a Scalar Function to Each Matrix Element with c(1, 2)
To explicitly call a function once for every matrix cell, set MARGIN = c(1, 2). The function receives a single value during each call.
M <- matrix(1:6, nrow = 2)
square_value <- function(x) {
x^2
}
result <- apply(M, c(1, 2), square_value)
print(M)
print(result)
Output
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
[,1] [,2] [,3]
[1,] 1 9 25
[2,] 4 16 36
The dimensions of the result remain the same because one result is returned for each row-column position.
Pass Additional Arguments to a Matrix Function
You can also pass additional arguments to the function. Provide the additional arguments to the function as parameters to apply() after the function argument.
In this example, we will pass an argument n to the function applied on each element of the matrix.
example.R
M = matrix(c(1:12), ncol=3)
incrementByN <- function(x, n=0) {
return(x+n)
}
y = apply(M, 2, incrementByN, n=6)
Output
> print(M)
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
> print(y)
[,1] [,2] [,3]
[1,] 7 11 15
[2,] 8 12 16
[3,] 9 13 17
[4,] 10 14 18
Here, n = 6 is forwarded to incrementByN(). Since MARGIN = 2, the function processes one column vector at a time and adds 6 to every value in that vector.
Apply Functions to Matrix Rows and Columns
Use MARGIN = 1 when the calculation should produce one result per row. Use MARGIN = 2 when it should produce one result per column.
M <- matrix(1:12, nrow = 4)
row_totals <- apply(M, 1, sum)
column_averages <- apply(M, 2, mean)
print(row_totals)
print(column_averages)
Output
[1] 15 18 21 24
[1] 2.5 6.5 10.5
The first result contains one sum for each row. The second contains one mean for each column.
Use Vectorized Operations for Simple Element-wise Calculations
R matrix arithmetic is already vectorized. You normally do not need apply() when the same built-in operation can be performed directly on every value.
M <- matrix(1:6, nrow = 2)
M_plus_2 <- M + 2
M_squared <- M^2
M_roots <- sqrt(M)
Expressions such as M + 2, M^2, and sqrt(M) operate directly on each matrix element. They are shorter and avoid the overhead of repeatedly calling a custom function.
Preserving Matrix Dimensions and Data Types
apply() simplifies its return value when possible. A row-wise or column-wise calculation that returns one value per row or column usually produces a vector. A transformation that returns multiple values may produce a matrix or an array.
Also note that apply() converts a data frame to a matrix before processing it. If the data frame contains mixed column types, values may be coerced to a common type such as character. Use matrix input for predictable numeric calculations.
Common Mistakes When Using apply() on Matrices
- Using
MARGIN = 2for a row calculation: use1for rows and2for columns. - Assuming the function always receives one value: with
MARGIN = 1or2, it receives a complete row or column vector. - Using
apply()for basic arithmetic: prefer direct expressions such asM * 2orlog(M). - Returning inconsistent result lengths: make sure the custom function returns results with a consistent structure for every row, column, or element.
- Ignoring missing values: pass arguments such as
na.rm = TRUEwhen the selected function supports them.
R Matrix apply() Questions
What does apply(matrix, 1, FUN) do in R?
It calls FUN once for each row of the matrix. Each call receives the complete row as a vector.
What does apply(matrix, 2, FUN) do?
It calls FUN once for each column. Each call receives the complete column as a vector.
How do I apply a function to each individual matrix element?
Use apply(M, c(1, 2), FUN) for an explicit per-element function call. For simple vectorized functions, use the function directly, such as sqrt(M) or M + 2.
How can I ignore NA values in apply()?
Pass na.rm = TRUE through ... when the function supports it. For example, apply(M, 1, mean, na.rm = TRUE) calculates each row mean after removing missing values.
Summary of Applying Functions to an R Matrix
Use apply() with MARGIN = 1 for row-wise operations, MARGIN = 2 for column-wise operations, and MARGIN = c(1, 2) for explicit element-by-element calls. Additional function arguments can be supplied after FUN. For simple element-wise arithmetic or built-in mathematical functions, direct vectorized matrix operations are generally the better choice.
In this R Tutorial, we learned how to apply a function on each element of a matrix using apply().
TutorialKart.com