← Back to R Course | Chapter 11: Apply Family | Lesson 2 of 6

lapply()

lapply runs a function on each item of a list and always gives back a list, like handing every child the same task and collecting all the results. It does the repeating for you.

In this page:

  1. lapply()
Syntax
r
result <- lapply(x, FUN)

lapply()

lapply(x, FUN) applies a function to every element of a vector or list and always returns a list, regardless of what the function itself returns.

It's the most general member of the apply family, since a list result can hold values of any type or length. Use lapply() when you don't need the result simplified to a vector.

Note: lapply() always returns a list -- use sapply() instead when you want the result automatically simplified to a vector.

Example: lapply()

markup
numbers <- list(1, 2, 3, 4)

squared <- lapply(numbers, function(x) x^2)
print(squared)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting a vector back from lapply, when it always returns a list; use sapply or unlist() for a vector.
  2. Writing the function with parentheses like lapply(x, sqrt()), which calls it instead of passing it.
  3. Using lapply on a data frame and forgetting it loops over columns, not rows.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.