用R计算矩阵中对称数据的平均值

用R计算矩阵中对称数据的平均值,r,matrix,R,Matrix,假设我有这样一个矩阵: A = matrix( c(2, 4, 3, 1, 5, 7, 4, 5, 1), # the data elements nrow=3, # number of rows ncol=3, # number of columns byrow = TRUE ) > A [,1] [,2] [,3] [1,] 2 4 3 [2,] 1 5

假设我有这样一个矩阵:

A = matrix( 
  c(2, 4, 3, 1, 5, 7, 4, 5, 1), # the data elements 
  nrow=3,              # number of rows 
  ncol=3,              # number of columns 
  byrow = TRUE
)     

> A
     [,1] [,2] [,3]
[1,]    2    4    3
[2,]    1    5    7
[3,]    4    5    1
> A.mean
     [,1] [,2] [,3]
[1,]  2.0  2.5  3.5
[2,]  2.5  5.0  6.0
[3,]  3.5  6.0  1.0
现在我想计算这个矩阵中对称数据的平均值,如下所示:

A = matrix( 
  c(2, 4, 3, 1, 5, 7, 4, 5, 1), # the data elements 
  nrow=3,              # number of rows 
  ncol=3,              # number of columns 
  byrow = TRUE
)     

> A
     [,1] [,2] [,3]
[1,]    2    4    3
[2,]    1    5    7
[3,]    4    5    1
> A.mean
     [,1] [,2] [,3]
[1,]  2.0  2.5  3.5
[2,]  2.5  5.0  6.0
[3,]  3.5  6.0  1.0
如何在不使用循环的情况下执行此操作?

请尝试:

(A+t(A))/2
#     [,1] [,2] [,3]
#[1,]  2.0  2.5  3.5
#[2,]  2.5  5.0  6.0
#[3,]  3.5  6.0  1.0
试试看:

(A+t(A))/2
#     [,1] [,2] [,3]
#[1,]  2.0  2.5  3.5
#[2,]  2.5  5.0  6.0
#[3,]  3.5  6.0  1.0

另一个选项是
Reduce

Reduce(`+`, list(A, t(A)))/2
#     [,1] [,2] [,3]
#[1,]  2.0  2.5  3.5
#[2,]  2.5  5.0  6.0
#[3,]  3.5  6.0  1.0

另一个选项是
Reduce

Reduce(`+`, list(A, t(A)))/2
#     [,1] [,2] [,3]
#[1,]  2.0  2.5  3.5
#[2,]  2.5  5.0  6.0
#[3,]  3.5  6.0  1.0