Display Correlation Tables as Descending List

蓝咒 提交于 2019-11-28 08:29:04

Here's one of many ways I could think to do this. I used the reshape package because the melt() syntax was easy for me to remember, but the melt() command could pretty easily be done with base R commands:

require(reshape)
## set up dummy data
a <- rnorm(100)
b <- a + (rnorm(100, 0, 2))
c <- a + b + (rnorm(100)/10)
df <- data.frame(a, b, c)
c <- cor(df)
## c is the correlations matrix

## keep only the lower triangle by 
## filling upper with NA
c[upper.tri(c, diag=TRUE)] <- NA

m <- melt(c)

## sort by descending absolute correlation
m <- m[order(- abs(m$value)), ]

## omit the NA values
dfOut <- na.omit(m)

## if you really want a list and not a data.frame
listOut <- split(dfOut, 1:nrow(dfOut))

Using base R (where cors is the correlation matrix):

up <- upper.tri(cors)
out <- data.frame(which(up, arr.ind=TRUE), cor=cors[up])
out <- out[!is.na(out$cor),]
out[order(abs(out$cor), decreasing=TRUE),]

Replace ... with your correlation call.

library(reshape)
x <- subset(melt(cor(...)), value != 1 | value != NA)
x <- x[with(x, order(-abs(x$value))),]

If you're getting a lot of NA in your correlations, perhaps try using the use="complete.obs" argument in your correlation call.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!