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:
Syntax
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()
numbers <- c(1, 2, 3, 4)
squared <- sapply(numbers, function(x) x^2)
print(squared)
cat(class(squared), "\n")
Login to try C/C++/Java/PHP code in the editor
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
- Expecting
sapplyto return a vector every time, when it may return a list if results have different lengths. - Using
sapplyon an empty input, which returnslist()instead of a vector. - Using
sapplywhere the type must be known, whenvapplychecks it.