矩阵列表中每个元素的均值 [英] Mean of each element of a list of matrices

查看:81
本文介绍了矩阵列表中每个元素的均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含三个矩阵的列表:

I have a list with three matrixes:

a<-matrix(runif(100))
b<-matrix(runif(100))
c<-matrix(runif(100))

mylist<-list(a,b,c)

我想获得三个矩阵中每个元素的均值.

I would like to obtain the mean of each element in the three matrices.

我试过:aaply(laply(mylist, as.matrix), c(1, 1), mean) 但这会返回每个矩阵的均值,而不是将每个元素的均值作为rowMeans() 会.

I tried: aaply(laply(mylist, as.matrix), c(1, 1), mean) but this returns the means of each matrix instead of taking the mean of each element as rowMeans() would.

推荐答案

也许你想要的是:

> set.seed(1)
> a<-matrix(runif(4)) 
> b<-matrix(runif(4))
> c<-matrix(runif(4))
> mylist<-list(a,b,c)  # a list of 3 matrices 
> 
> apply(simplify2array(mylist), c(1,2), mean)
          [,1]
[1,] 0.3654349
[2,] 0.4441000
[3,] 0.5745011
[4,] 0.5818541

apply 调用中 MARGIN 的向量 c(1,2) 表示函数 mean 应该应用于行和列(同时),请参阅 ?apply 了解更多详情.

The vector c(1,2) for MARGIN in the apply call indicates that the function mean should be applied to rows and columns (both at once), see ?apply for further details.

另一种选择是使用 Reduce 函数

Another alternative is using Reduce function

> Reduce("+", mylist)/ length(mylist)
          [,1]
[1,] 0.3654349
[2,] 0.4441000
[3,] 0.5745011
[4,] 0.5818541

这篇关于矩阵列表中每个元素的均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆