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

隐身守侯 提交于 2019-11-30 19:03:53

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