![](/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.