R Apply Family

Loops (like for, while and repeat) are a way to repeatedly execute some code.

However, they are often slow in execution when it comes to processing large data sets.

R has a more efficient and quick approach to perform iterations – The apply family.

Apply family in R

The apply family consists of vectorized functions. Below are the most common forms of apply functions.

  • apply()
  • lapply()
  • sapply()
  • tapply()

These functions let you take data in batches and process the whole batch at once.

There primary difference is in the object (such as list, matrix, data frame etc.) on which the function is applied to and the object that will be returned from the function.

apply() function

The apply() function is used to apply a function to the rows or columns of matrices or data frames.

It assembles the returned values into a vector, and then returns that vector.

If you want to apply a function on a data frame, make sure that the data frame is homogeneous (i.e. either all numeric values or all character strings)

Otherwise, R will force all columns to have identical types. This may not be what you want.

In that case, use the lapply or sapply functions.

Syntax

The syntax for apply() is as follows:

apply(x,MARGIN,FUN,)

Parameters

apply() function parameters
ParameterConditionDescription
xRequiredA matrix , data frame or array
MARGINRequiredA vector giving the subscripts which the function will be applied over.
1 indicates rows
2 indicates columns
c(1, 2) indicates rows and columns
FUNRequiredThe function to be applied
OptionalAny other arguments to be passed to the FUN function

Examples

Example: Get the sum of each column

> data <- matrix(1:9, nrow=3, ncol=3)
> data
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

> apply(data, 2, sum)
[1]  6 15 24

Example: Get the sum of each row

> data <- matrix(1:9, nrow=3, ncol=3)
> data
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

> apply(data, 1, sum)
[1] 12 15 18

You can use user-defined functions as well.

Example: Apply a custom function that squares each element in a matrix

> data <- matrix(1:9, nrow=3, ncol=3)
> data
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

> apply(data, 2, function(x){x^2})
     [,1] [,2] [,3]
[1,]    1   16   49
[2,]    4   25   64
[3,]    9   36   81

lapply() function

The lapply() function is used to apply a function to each element of the list.

It collects the returned values into a list, and then returns that list.

Syntax

The syntax for lapply() is as follows:

lapply(x,FUN,)

Parameters

lapply() function parameters
ParameterConditionDescription
xRequiredA list
FUNRequiredThe function to be applied
OptionalAny other arguments to be passed to the FUN function

Example

Example: Get the sum of each list item

> data <- list(item1 = 1:5,
+              item2 = seq(4,36,8),
+              item4 = c(1,3,5,7,9))
> data
$item1
[1] 1 2 3 4 5

$item2
[1]  4 12 20 28 36

$item4
[1] 1 3 5 7 9

> lapply(data, sum)
$item1
[1] 15

$item2
[1] 100

$item4
[1] 25

sapply() function

The sapply() and lapply() work basically the same.

The only difference is that lapply() always returns a list, whereas sapply() tries to simplify the result into a vector or matrix.

  • If the return value is a list where every element is length 1, you get a vector.
  • If the return value is a list where every element is a vector of the same length (> 1), you get a matrix.
  • If the lengths vary, simplification is impossible and you get a list.

Syntax

The syntax for sapply() is as follows:

sapply(x,FUN,)

Parameters

sapply() function parameters
ParameterConditionDescription
xRequiredA list
FUNRequiredThe function to be applied
OptionalAny other arguments to be passed to the FUN function

Example

Example: Get the sum of each list item and simplify the result into a vector

> data <- list(item1 = 1:5,
+              item2 = seq(4,36,8),
+              item4 = c(1,3,5,7,9))
> data
$item1
[1] 1 2 3 4 5

$item2
[1]  4 12 20 28 36

$item4
[1] 1 3 5 7 9

> sapply(data, sum)
item1 item2 item4 
   15   100    25

tapply() function

The tapply() function breaks the data set up into groups and applies a function to each group.

Syntax

The syntax for tapply() is as follows:

tapply(x,INDEX,FUN,,simplify)

Parameters

tapply() function parameters
ParameterConditionDescription
xRequiredA vector
INDEXRequiredA grouping factor or a list of factors
FUNRequiredThe function to be applied
OptionalAny other arguments to be passed to the FUN function
simplifyOptionalReturns simplified result if set to TRUE.
Default is TRUE.

Example

Example: Find the age of youngest male and female

> data <- data.frame(name=c("Amy","Max","Ray","Kim","Sam","Eve","Bob"),
+                    age=c(24, 22, 21, 23, 20, 24, 21),
+                    gender=factor(c("F","M","M","F","M","F","M")))
> data
  name age gender
1  Amy  24      F
2  Max  22      M
3  Ray  21      M
4  Kim  23      F
5  Sam  20      M
6  Eve  24      F
7  Bob  21      M

> tapply(data$age, data$gender, min)
 F  M 
23 20