How to Calculate the Average of List in R

To calculate an average of a list in R, use the sapply() and mean() functions. The sapply() function applies a function to all the elements of the list.

To create a list in R, use the list() function.

To create a Vector in R, use the c() function or colon operator.

Example 1

pedro <- 1:4
bella <- 5:8

lastOfUs <- list(pedro, bella, pedro * 2, bella * 3)
lastOfUs

cat("After finding the average of each element of the list", "\n")
sapply(lastOfUs, mean)

Output

[[1]]
[1] 1 2 3 4

[[2]]
[1] 5 6 7 8

[[3]]
[1] 2 4 6 8

[[4]]
[1] 15 18 21 24

After finding the average of each element of the list

[1] 2.5 6.5 5.0 19.5

You can see from the output that the average of the first element is 2.5 because (1 + 2 + 3 +5) / 4 = 2.5.

Same for the second, third, and fourth elements.

To get the mean of the 4th element of the list, use the mean(list[[4]]).

To get the mean of each element of the list, use lapply(list, mean).

Example 2

Let’s find the average of the fourth element of our lastOfUs list.

pedro <- 1:4
bella <- 5:8

lastOfUs <- list(pedro, bella, pedro * 2, bella * 3)
lastOfUs

cat("After finding the average of fourth element of the list", "\n")
mean(lastOfUs[[4]])

Output

[[1]]
[1] 1 2 3 4

[[2]]
[1] 5 6 7 8

[[3]]
[1] 2 4 6 8

[[4]]
[1] 15 18 21 24

After finding the average of fourth element of the list

[1] 19.5

And we get the average of the fourth element.

That’s it.

Leave a Comment