How to use the Apply function in R


Previously we showed you how to write a loop in R. Very often it’s a better idea to use the apply function in R than to write a loop.

So what is the apply function in R?

Well, apply is really a family of functions that have varying uses. Here are the available R apply functions: apply, lapply, sapply, vapply, mapply, rapply and tapply.

Apply is the head of the family. Apply operates on arrays: apply(X, MARGIN, FUN, …). This will return a vector or array or list of values obtained by applying a function to margins of an array.

The Arguments are the following:
X – the array to be used.

MARGIN – a vector giving the subscripts which the function will be applied over. 1 indicates rows, 2 indicates columns, c(1,2) indicates rows and columns.

FUN – the function to be applied: see Details. In the case of functions like +, %*%, etc., the function name must be backquoted or quoted.

… – optional arguments to FUN.

Lets look at an example:

>cars #built-in dataset Speed and Stopping Distances of Cars

I won’t type the entire print but here are a few rows:

speed dist
1      4    2
2      4   10
3      7    4
4      7   22
5      8   16

This goes to row 50.

What if we wanted to get the sum of speed?

speed  dist 
770  2149

What if you wanted to get the mean?

> apply(cars,2,mean)
speed  dist 
15.40 42.98

These are basic examples of using the apply function in R. Next we will look at the other family members of apply.