How to Calculate the Mean for Every List Item in R (Example Code)
In this tutorial you’ll learn how to use a function such as mean() or sum() for every element of a list in the R programming language.
Example Data
x <- list(1:10, # Constructing example list in R 20:15, 2:8) x # Display example list in RStudio console # [[1]] # [1] 1 2 3 4 5 6 7 8 9 10 # # [[2]] # [1] 20 19 18 17 16 15 # # [[3]] # [1] 2 3 4 5 6 7 8 |
x <- list(1:10, # Constructing example list in R 20:15, 2:8) x # Display example list in RStudio console # [[1]] # [1] 1 2 3 4 5 6 7 8 9 10 # # [[2]] # [1] 20 19 18 17 16 15 # # [[3]] # [1] 2 3 4 5 6 7 8
Example: Using lapply() Function to Get Mean of Each List Element
lapply(x, mean) # Using lapply and mean # [[1]] # [1] 5.5 # # [[2]] # [1] 17.5 # # [[3]] # [1] 5 |
lapply(x, mean) # Using lapply and mean # [[1]] # [1] 5.5 # # [[2]] # [1] 17.5 # # [[3]] # [1] 5
Related Articles & Further Resources
You may find some further R programming tutorials on topics such as coding errors, lists, data elements, and extracting data in the following list: