list 如何在R中的列表元素上应用均值函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13353315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:55:35  来源:igfitidea点击:

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

rlistlapply

提问by hora

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:

我有一个列表,我想用它lapply()来计算其元素的平均值。例如,对于列表的第七项,我有:

>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()像下面这样使用时,结果会是别的东西。我该怎么办?

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

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

回答by

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.

要获得列表中第 7 个元素的平均值,只需使用mean(list[[7]]). 要获取列表中每个元素的平均值,请使用lapply(list,mean). 调用你的 list 是一个非常糟糕的主意list

回答by Ricardo Saporta

consider using sapplyinstead of lapply.

考虑使用sapply代替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






此外,您可能想看看plyrplyr包装。 This question这个问题也很好地解释了不同的 *apply 函数