How to apply mean function over elements of a list in R

hora picture hora · Nov 13, 2012 · Viewed 44.4k times · Source

I have a list and I want to use lapply() to compute the mean of its elements. For example, for the seventh item of the list I have:

>list[[7]]
 [1] 1 1 1 1 1 1 1 1 1 1

and my output should be:

> mean(temp[[7]][1:10])
[1] 1

But when I use lapply() like below the result would be something else. What should I do?

> lapply(list[[7]][1:10],mean)
[[1]]
[1] 1

[[2]]
[1] 1
.
.
.
[[10]]
[1] 1

Answer

user399470 picture user399470 · Nov 13, 2012

To get the mean of the 7th element of the list just use mean(list[[7]]). To get the mean of each element of the list use lapply(list,mean). And it's a really bad idea to call your list list.