Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

sum - R - min, max and mean of off-diagonal elements in a matrix

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

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

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

to use:

colMeans(dataD) # get the mean for columns

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

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

and the lower off diagonal via this:

> 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..

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...