Applying Function to All Matrix Elements in R (Example Code)

In this tutorial, I’ll explain how to apply a function or command to all matrix elements in R programming.

Example Data

my_matrix <- matrix(10:29, ncol = 5)    # Example matrix in R
my_matrix                               # Print example matrix to RStudio console
#      [,1] [,2] [,3] [,4] [,5]
# [1,]   10   14   18   22   26
# [2,]   11   15   19   23   27
# [3,]   12   16   20   24   28
# [4,]   13   17   21   25   29

Example: Create Own Function & Apply to Each Matrix Element

own_function <- function(x) {           # User-defined function in R
  (x / 5 + 30) * x
}
apply(my_matrix,                        # Applying own function to each matrix element
      c(1, 2),
      own_function)
#       [,1]  [,2]  [,3]  [,4]   [,5]
# [1,] 320.0 459.2 604.8 756.8  915.2
# [2,] 354.2 495.0 642.2 795.8  955.8
# [3,] 388.8 531.2 680.0 835.2  996.8
# [4,] 423.8 567.8 718.2 875.0 1038.2

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top