![](/img/trans.png)
[英]How do I get regression coefficients from a variance covariance matrix in R?
[英]How do I get the unique pairs from a Covariance Matrix?
我试图从通过 R 代码获得的协方差矩阵中获取唯一对。 这是我到目前为止所尝试的:
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,]
我很确定我接近正确答案:如果我的数学没有错的话,大约有 6对独特的配对。 有人可以帮帮我吗?
将对角线和上三角形设置为一些特殊值(在下面的示例中为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
或者如果你想在没有reshape2
的情况下做到这一点
data.frame(m) %>%
mutate(rows = rownames(.)) %>%
gather(cols, val, -rows) %>%
filter(val != Inf)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.