R – Apply Function to each Element of a Matrix
We can apply a function to each element of a Matrix, or only to specific dimensions, using apply().
Syntax – apply()
The syntax of apply() function in R is
</>
Copy
apply(X, MARGIN, FUN, ...)
where
X
an array or a matrixMARGIN
is a vector giving the subscripts which the function will be applied over.
For a matrix 1 indicates rows, 2 indicates columns, c(1,2) indicates rows and
columns.
If X has named dimension names, it can be a character vector selecting
dimension names.FUN
is the function to be applied on the element(s) of x
Apply Function on each Element of a Matrix
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.
example.R
</>
Copy
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 Function on each Element of a Matrix – Pass Additional Arguments to the 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
</>
Copy
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
Conclusion
In this R Tutorial, we learned how to apply a function on each element of a matrix using apply()
.