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:
Syntax
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()
numbers <- list(1, 2, 3, 4)
squared <- lapply(numbers, function(x) x^2)
print(squared)
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 a vector back from
lapply, when it always returns a list; usesapplyorunlist()for a vector. - Writing the function with parentheses like
lapply(x, sqrt()), which calls it instead of passing it. - Using
lapplyon a data frame and forgetting it loops over columns, not rows.