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 values 1 and 2 to define where the function should be applied.

  • FUN: This represents the function that needs to be applied to each element of the vector-like object X.

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() function
x = apply(mymatrix, 1, min)
x
# using margin value as 2
y = apply(mymatrix, 2, min)
y

Code explanation

  • Line 1: We create a matrix variable, mymatrix, with 3 rows and 4 columns, using the matrix() function.

  • Line 8: We implement the apply() function on the mymatrix matrix, using a margin value of 1 and taking the min value of the elements in the row. The result is assigned to a variable x.

  • Line 9: We print the variable x.

  • Line 12: We implement the apply() function on the mymatrix matrix , using a margin value of 2 and taking the min value of the elements in the row. The result is assigned to a variable y.

  • Line 13: We print the variable y.

Free Resources