I am trying to get the unique pairs from a covariance matrix obtained through R code. 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. 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
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
data.frame(m) %>%
mutate(rows = rownames(.)) %>%
gather(cols, val, -rows) %>%
filter(val != Inf)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.