Everything you want to know about the R apply functions

Adrian Joseph, PhD
6 min readAug 12, 2022

Use cases, examples, benchmarking.

Image made by author.

What is the apply family?

for loops are the joy and the curse of any developer. They are instinctive to write, as they are a direct representation of how we think. “Go over this vector and apply this function to each column” becomes for (i in myVec){myFun(i)}. Yet, for loops are inefficient and ugly. Being ugly is not just an aesthetic problem: it is a readability and maintainability problem.

So how can we drop for loops, or at least most of them? How can we make our code faster and more readable?

Enter the apply family.

The apply family is part of base R. No need to install any extra package to use them. The apply functions simplify applying a set of operations to vectors, data frames, matrices, or lists. And of course, apply functions are significantly faster than a for loop.

The apply family has several members:

  • apply
  • lapply
  • tapply
  • mapply
  • vapply
  • sapply
  • replicate

Let’s have a look at all of them in detail. I will give you examples, use cases, and benchmarking. I will…

--

--