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

sapply()

sapply works like lapply but tidies the answers into a simple vector when it can, like collecting the results into one neat row. It is a friendlier version for simple cases.

In this page:

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

sapply()

sapply(x, FUN) works like lapply() but tries to simplify the result into a vector or matrix when possible, instead of always returning a list.

This makes it more convenient than lapply() for the common case where each call produces a single value. If simplification isn't possible, sapply() falls back to returning a list, just like lapply().

Note: sapply() is essentially "lapply() plus automatic simplification" -- reach for it first, and use lapply() when you specifically need a list.

Example: sapply()

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

squared <- sapply(numbers, function(x) x^2)
print(squared)
cat(class(squared), "\n")
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 sapply to return a vector every time, when it may return a list if results have different lengths.
  2. Using sapply on an empty input, which returns list() instead of a vector.
  3. Using sapply where the type must be known, when vapply checks it.
🔒

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.