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

假装没事ソ 提交于 2019-11-30 03:15:10

问题


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

回答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.




回答2:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!