What is the apply() function in R?
Overview
The apply() function in R is used to apply the function family (mean, mode, median, and so on) on each vector element or list element.
Syntax
apply(X, MARGIN, FUN = NULL)
Parameter value
The apply() function takes the following parameter values:
-
X: This represents a vector-like object. -
MARGIN: This takes any of the values1and2to define where the function should be applied. -
FUN: This represents the function that needs to be applied to each element of the vector-like objectX.
Return value
The apply() function returns a list or an array of values.
Code example
mymatrix = matrix( c( 1, 19, 513,4173,8, 12, 281,6932,7, 15, 801,7121),nrow=3,ncol=4)# calling the apply() functionx = apply(mymatrix, 1, min)x# using margin value as 2y = apply(mymatrix, 2, min)y
Code explanation
-
Line 1: We create a matrix variable,
mymatrix, with3rows and4columns, using thematrix()function. -
Line 8: We implement the
apply()function on themymatrixmatrix, using amarginvalue of1and taking theminvalue of the elements in the row. The result is assigned to a variablex. -
Line 9: We print the variable
x. -
Line 12: We implement the
apply()function on themymatrixmatrix , using amarginvalue of2and taking theminvalue of the elements in the row. The result is assigned to a variabley. -
Line 13: We print the variable
y.