Apply a Function over a List of elements in R Programming – lapply() Function
Last Updated :
24 Jun, 2022
lapply() function in R Programming Language is used to apply a function over a list of elements.
lapply() function is used with a list and performs the following operations:
lapply(List, length): Returns the length of objects present in the list, List.
lapply(List, sum): Returns the sum of elements held by objects in the list, List.
lapply(List, mean): Returns the mean of elements held by objects in the list, List.
lapply(List, cumsum): Returns the cumulative sum of elements held by objects present inside the list, List.
Syntax: lapply(list, func)
Parameters:
R – Apply a Function over a List of elements
Example 1: Basic example of lapply() Function in R programming
R
A = matrix (1:9, 3, 3)
B = matrix (10:18, 3, 3)
myList = list (A, B)
determinant = lapply (myList, det)
print (determinant)
|
Output:
[[1]]
[1] 0
[[2]]
[1] 5.329071e-15
Example 2: Apply a Function over a List of elements in R
R
A = matrix (1:9, 3, 3)
B = matrix (10:18, 3, 3)
myList = list (A, B)
sum = lapply (myList, sum)
print (sum)
|
Output:
[, 1] [, 2] [, 3]
[1, ] 1 4 7
[2, ] 2 5 8
[3, ] 3 6 9
[1] 28 80 162
[1] 6 120 504
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...