R-矩阵中非对角元素的最小值,最大值和均值 [英] R - min, max and mean of off-diagonal elements in a matrix

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

问题描述

我就像R中的矩阵,我想得到:

I have like a matrix in R and I want to get:

Max off - diagonal elements
Min off – diagonal elements
Mean off –diagonal elements

使用对角线时,我使用了max(diag(A)),min(diag(A)),mean(diag(A)),并且工作得很好

With diagonal I used max(diag(A)) , min(diag(A)) , mean(diag(A)) and worked just fine

但是对于非对角线,我尝试了

But for off-diagonal I tried

dataD <- subset(A, V1!=V2)

Error in subset.matrix(A, V1 != V2) : object 'V1' not found

使用:

colMeans(dataD) # get the mean for columns

但是我无法获得dataD b/c,它表示未找到对象'V1'

but I cannot get dataD b/c it says object 'V1' not found

谢谢!

推荐答案

row()col()辅助函数在这里很有用.使用@James A,我们可以使用以下小技巧获得对角线上方的位置:

Here the row() and col() helper functions are useful. Using @James A, we can get the upper off-diagonal using this little trick:

> A[row(A) == (col(A) - 1)]
[1]  5 10 15

和下面的对角线:

> A[row(A) == (col(A) + 1)]
[1]  2  7 12

这些可以概括为任意所需的对角线:

These can be generalised to give whatever diagonals you want:

> A[row(A) == (col(A) - 2)]
[1]  9 14

并且不需要任何子设置.

and don't require any subsetting.

然后,只需对这些值调用所需的任何函数,就很简单了.例如:

Then it is a simple matter of calling whatever function you want on these values. E.g.:

> mean(A[row(A) == (col(A) - 1)])
[1] 10

如果根据我的评论,您说的是除对角线以外的所有内容,请使用

If as per my comment you mean everything but the diagonal, then use

> diag(A) <- NA
> mean(A, na.rm = TRUE)
[1] 8.5
> max(A, na.rm = TRUE)
[1] 15
> # etc. using sum(A, na.rm = TRUE), min(A, na.rm = TRUE), etc..

因此,这不会丢失,Ben Bolker建议(在评论中)可以使用我上面提到的row()col()函数更巧妙地完成上述代码块:

So this doesn't get lost, Ben Bolker suggests (in the comments) that the above code block can be done more neatly using the row() and col() functions I mentioned above:

mean(A[row(A)!=col(A)])
min(A[row(A)!=col(A)])
max(A[row(A)!=col(A)])
sum(A[row(A)!=col(A)])

这是一个更好的解决方案.

which is a nicer solution all round.

这篇关于R-矩阵中非对角元素的最小值,最大值和均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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