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

sapply()

In this page:

  1. sapply()

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")
🔒

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.