R - 矩阵中非对角线元素的最小值、最大值和平均值 [英] R - min, max and mean of off-diagonal elements in a matrix
问题描述
我在 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
并且不需要任何子集.
然后在这些值上调用您想要的任何函数是一件简单的事情.例如:
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屋!