Press "Enter" to skip to content

Reasons to Prefer apply() over For Loops in R

Hugo Gruson draws some comparisons:

The debate regarding the use of for loops versus the apply() function family (apply()lapply()vapply(), etc., along with their purrr counterparts: map()map2()map_lgl()map_chr(), etc.), has been a longstanding one in the R community.

While you may occasionally hear that for loops are slower, this notion has already been debunked in other posts. When utilized correctly, a for loop can achieve performance on par with apply() functions.

However, there are still lesser-known reasons to prefer apply() functions over for loops, which we will explore in this post.

Read on for an important caveat, and then several reasons to prefer apply() (or purrr’s counterparts). H/T R-Bloggers.