假设我有一个这样的矩阵:
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
如何在不使用循环的情况下执行此操作?
答案 0 :(得分:6)
试试吧:
(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
答案 1 :(得分:1)
另一个选项是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