mapply and by functions in R

In the previous tutorial we looked at the apply group of functions. In this example we look at mapply and by functions.

Its a bit difficult to explain the mapply function in words so we directly jump into an example and provide a definition later on.

Requires explanation, doesn’t it? So here’s how it goes – the first argument is the function FUN. It takes in two parameters x and y. The values of x come from the second argument (x=c(2,3)) and the values of y come from the 3rd argument (y=c(3,4)). x and y both have two values so the function is called twice. The first time its called with the first values of x and y (x=2 and y =3 which gives 8). The second time its called with the second values of x and y (x=3 and y=4 which gives 81)

Definition of mapply function

As promised, here is the formal definition – mapply can be used to call a function FUN over vectors or lists one index at a time. In other words the function is first called over elements at index 1 of all vectors or list, its then called over all elements at index 2 and so on.

The arguments x and y are recycled if they are of different lengths. (however they have to be either all 0 or all non zero)

You can’t do this though

Its not necessary to specify names

We can give names to each index. The names from the first argument is used.

unless you specifically ask R to not use names

If the function needs more arguments that remain same for all the iterations of FUN then use “MoreArgs” argument

The values z and k are 1 and 2 respectively. So the first evaluation of function gives (2+2)^(3+1) and the second gives (3+2)^(4+1)

As with the other apply functions you can use Simplify to reduce the result to a vector, matrix or array


The by function is similar to apply function but is used to apply functions over data frame or matrix. We first create a data frame for this example.

We use the by function to get sum of all values of a grouped by values of b. That is, sum of all values of a where b=1, sum of all values of a where b is 2 and so on.

The by function takes 3 variables. The first is the data frame. The second is the factors over which the function has to be applied. The length of this argument should be same as the length of the data frame. The third is the actual function. This is what it produces

Even if the data frame has multiple columns the function works well.

Leave a Reply

Your email address will not be published. Required fields are marked *