Programming in R - tutorial : apply() function in R :

Author: Abhinav Agrawal

apply() function in R comes handy when it comes to applying a specific operation/function on the margins (across rows or columns) of a an array or matrix.

Syntax: apply(X, MARGIN, FUN,…)

X = an array or matrix MARGIN can 1 indicating operation or function to be performed on rows, 2 for columns or could be expressed using combine function c(1, 2) indicates both rows and columns or basically indicating that the operation needs to be performed on all the elements of the rows and columns.

FUN = Function or operation that needs to be performed

… other optional arguments passed to the function

m1 <- c(1, 2, 3, 4, 5, 6, 7, 8)  # m1 is the sequence of elements
dim(m1) <- c(2, 4)  # define the dimensions of object m1 
m1  # print the matrix m1
##      [,1] [,2] [,3] [,4]
## [1,]    1    3    5    7
## [2,]    2    4    6    8

Performing apply() function on the matrix object m1

apply(m1, 1, sum)  # sum operation on rows. Output would be rowsum basically
## [1] 16 20
apply(m1, 2, sum)  # sum operation on column. Output would be columnsum basically
## [1]  3  7 11 15
apply(m1, c(1, 2), function(x) x * 10)  # multiplying each element by 10
##      [,1] [,2] [,3] [,4]
## [1,]   10   30   50   70
## [2,]   20   40   60   80