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
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
.
Ricardo Saporta
consider using sapply
instead of lapply
.
# sample data
a<- 1:3
dat <- list(a, a*2, a*3)
# sapply gives a tidier output
> sapply(dat, mean)
[1] 2 4 6
> lapply(dat, mean)
[[1]]
[1] 2
[[2]]
[1] 4
[[3]]
[1] 6
Also, you might want to take a look at the
plyr
package. This question also does a good job of explaining the different *apply functions
来源:https://stackoverflow.com/questions/13353315/how-to-apply-mean-function-over-elements-of-a-list-in-r