平均对角减去一

时间:2015-10-19 09:17:30

标签: r matrix diagonal

是否可以计算矩阵对角线下对角线1的平均值?

    a1  a2  a3  a4  a5
a1  0   1   1   1   1
a2  2   0   1   1   1
a3  1   3   0   1   1
a4  1   1   4   0   1
a5  1   1   1   5   0

我想计算2 + 3 + 4 + 5

的平均值

2 个答案:

答案 0 :(得分:6)

是。我认为(和R一样)有各种各样的方法,但这里有一个。它使用base-R中的res <- mean(diag(mm[-1,-ncol(mm)])) 函数,并在获取对角线并计算其平均值之前删除第一行和最后一列。

mm <- structure(c(0L, 2L, 1L, 1L, 1L, 1L, 0L, 3L, 1L, 1L, 1L, 1L, 0L, 
4L, 1L, 1L, 1L, 1L, 0L, 5L, 1L, 1L, 1L, 1L, 0L), .Dim = c(5L, 
5L), .Dimnames = list(c("a1", "a2", "a3", "a4", "a5"), c("a1", 
"a2", "a3", "a4", "a5")))

使用的数据:

sudo /Applications/XAMPP/xamppfiles/bin/pecl install mongo

fatal error: openssl/evp.h: No such file or directory
 #include <openssl/evp.h>
                         ^
compilation terminated.
make: *** [io_stream.lo] Error 1
ERROR: `make' failed
PEAR Version: 1.9.4 PHP Version: 5.5.28

答案 1 :(得分:5)

这是一种可能性

mean(m[col(m) == (row(m) - 1)])
## [1] 3.5

这里的想法是获取列和行索引,然后仅选择 column == row - 1 时的值(正好在对角线下方 - 因为对角线是 col ==行

数据

m <- structure(c(0L, 2L, 1L, 1L, 1L, 1L, 0L, 3L, 1L, 1L, 1L, 1L, 0L, 
4L, 1L, 1L, 1L, 1L, 0L, 5L, 1L, 1L, 1L, 1L, 0L), .Dim = c(5L, 
5L), .Dimnames = list(c("a1", "a2", "a3", "a4", "a5"), c("a1", 
"a2", "a3", "a4", "a5")))