简体   繁体   English

如何从协方差矩阵中获取唯一对?

[英]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.

相关问题 如何从R中的方差协方差矩阵中获得回归系数? - How do I get regression coefficients from a variance covariance matrix in R? 如何通过MATLAB代码在R中创建协方差矩阵? - How do I create a covariance matrix in R from MATLAB code? 如何在平方协方差矩阵中组织协方差对列表? - How to organize a list of covariance pairs in a squared covariance matrix? 如何从矩阵单元中提取值对? - How do I extract pairs of values from matrix cells? 如何从具有虚拟变量的数据中找到相关性和协方差矩阵? - How do I find the correlation and the covariance matrix from a data with a dummy variable? 如何通过唯一的组/子组对找到不等式的总和? - How do I find the sum of inequalities by unique group/subgroup pairs? 在给定协方差矩阵和拟合系数的情况下,如何计算线性回归的p值 - How do I calculate p values of a linear regression given the covariance matrix and fit coefficients 如何绘制在网络中链接的代理的唯一对? - How do I draw unique pairs of agents who are linked in a network? 如何从ff_matrix有效地计算协方差矩阵 - How to efficiently calculate a covariance matrix from an ff_matrix 如何从稀疏矩阵中获取行列对 - how to get row-column pairs from sparse matrix
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM