it feels to me like this question should have been answered before but I couldn't find it anywhere. How can I extract the upper triangle of a symmetrical matrix in R? I want to calculate the mean of such a matrix, but without the 0s in the diagonal, since they will tint my results. I have this code:
library(Matrix)
matrix <- as.matrix(distObject)
m[lower.tri(m)] <- 0
triu(m)
Currently this gets me:
V2 V3 V4 V5 V6 V7
V2 0.0000000 0.4946237 0.6834532 0.6653992 0.6881029 0.6438849
V3 . 0.0000000 0.7183673 0.6531532 0.6959707 0.6458333
V4 . . 0.0000000 0.4024896 0.6845238 0.7075472
V5 . . . 0.0000000 0.6901840 0.6843854
V6 . . . 0.0000000 0.3821429
V7 . . . . . 0.0000000
However, I need something like:
V3 V4 V5 V6 V7
V3 0.4946237 0.6834532 0.6653992 0.6881029 0.6438849
V4 . 0.7183673 0.6531532 0.6959707 0.6458333
V5 . . 0.4024896 0.6845238 0.7075472
V6 . . . 0.6901840 0.6843854
V7 . . . 0.3821429
Would be great if someone would be able to help!
Thanks to @user20650 I found this code that does exactly what I want:
library(Matrix)
m <- as.matrix(distObject)
m[lower.tri(m)] <- 0
m <- m[-nrow(m),-1]
triu(m)