Apply a Function over a List of elements in R Programming – lapply() Function

lapply() function in R Language is used to apply a function over a list of elements.

Syntax: lapply(list, func)

Parameters:
list: list of elements
func: operation to be applied

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate 
# lapply() function 
    
# Creating a matrix 
A = matrix(1:9, 3, 3
    
# Creating another matrix 
B = matrix(10:18, 3, 3)  
    
# Creating a list 
myList = list(A, B) 
    
# applying lapply() 
determinant = lapply(myList, det) 
print(determinant) 

chevron_right


Output:

[[1]]
[1] 0

[[2]]
[1] 5.329071e-15

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate 
# lapply() function 
    
# Creating a matrix 
A = matrix(1:9, 3, 3
    
# Creating another matrix 
B = matrix(10:18, 3, 3)  
    
# Creating a list 
myList = list(A, B) 
    
# applying lapply() 
sum = lapply(myList, sum
print(sum

chevron_right


Output:

     [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9
[1]  28  80 162
[1]   6 120 504



My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.