[英]How do I get the unique pairs from a Covariance Matrix?
I am trying to get the unique pairs from a covariance matrix obtained through R code.我试图从通过 R 代码获得的协方差矩阵中获取唯一对。 This is what I have tried so far:
这是我到目前为止所尝试的:
data <- tibble(x = 1:3, y = 2:4, z = 3:5, w = 10:12)
cov_m <- reshape2::melt(cov(data)) %>%
filter(Var1 != Var2) # I do this expecting to remove Cov(Var1, Var1) or similar cases
cov_m <- cov_m[duplicated(m_cov$Var1,]
I'm pretty sure I'm close to the right answer: about 6 unique pairs if my math isn't wrong.我很确定我接近正确答案:如果我的数学没有错的话,大约有 6对独特的配对。 Could somebody help me out?
有人可以帮帮我吗?
Set the diagonal and upper triangle to be some special value ( Inf
in example below) and then remove them after doing melt
将对角线和上三角形设置为一些特殊值(在下面的示例中为
Inf
),然后在melt
后将其移除
m = cov(data)
m[upper.tri(m)] = Inf
diag(m) = Inf
d = reshape2::melt(m)
d[d$value != Inf,]
# Var1 Var2 value
#2 y x 1
#3 z x 1
#4 w x 1
#7 z y 1
#8 w y 1
#12 w z 1
Or if you want to do it without reshape2
或者如果你想在没有
reshape2
的情况下做到这一点
data.frame(m) %>%
mutate(rows = rownames(.)) %>%
gather(cols, val, -rows) %>%
filter(val != Inf)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.