0
0
R-programmingHow-ToBeginner ยท 3 min read

How to Use lapply in R: Syntax, Examples, and Tips

In R, lapply applies a function to each element of a list and returns a list of the same length. It is useful for running the same operation on multiple items without writing loops.
๐Ÿ“

Syntax

The basic syntax of lapply is:

  • X: a list or vector to process
  • FUN: the function to apply to each element
  • Additional arguments can be passed to FUN
r
lapply(X, FUN, ...)
๐Ÿ’ป

Example

This example shows how to use lapply to square each number in a list.

r
numbers <- list(a = 1, b = 2, c = 3)
squared <- lapply(numbers, function(x) x^2)
print(squared)
Output
$a [1] 1 $b [1] 4 $c [1] 9
โš ๏ธ

Common Pitfalls

Common mistakes include expecting lapply to return a vector instead of a list, or forgetting to use an anonymous function when extra arguments are needed.

Also, using sapply might be better if you want a simplified result like a vector or matrix.

r
values <- list(1, 2, 3)
# Wrong: expecting a vector
result_wrong <- lapply(values, sqrt)
print(result_wrong)  # returns a list

# Right: simplify with sapply
result_right <- sapply(values, sqrt)
print(result_right)  # returns a numeric vector
Output
[[1]] [1] 1 [[2]] [1] 1.414214 [[3]] [1] 1.732051 [1] 1.000000 1.414214 1.732051
๐Ÿ“Š

Quick Reference

ParameterDescription
XList or vector to apply the function on
FUNFunction to apply to each element
...Additional arguments passed to FUN
ReturnList of results with same length as X
โœ…

Key Takeaways

Use lapply to apply a function to each element of a list and get a list back.
Remember lapply always returns a list, even if the result looks like a vector.
Use anonymous functions inside lapply to customize operations easily.
For simpler output like vectors, consider using sapply instead.
Pass extra arguments to the function via lapply's ... parameter.