将相关表显示为降序列表 [英] Display Correlation Tables as Descending List

查看:81
本文介绍了将相关表显示为降序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在具有很多变量的时间序列上运行cor()时,我得到一个表格表,其中每个变量都有行和列,显示了它们之间的相关性。

When running cor() on a times series with a lot of variables, I get a table back that has a row and column for each variable, showing the correlation between them.

我如何查看此表为从最相关到​​最不相关的列表(消除所有NA结果和映射回自身的结果(即A与A的相关性))。我还想将反向(负)结果视为绝对值,但仍将它们显示为负。

How can I view this table as a list from most correlated to least correlated (eliminating all NA results and results that map back to themselves (i.e. the correlation of A to A)). I would also like to count inverse (negative) results as absolute values, but still show them as negative.

因此,所需的输出将类似于:

So the desired output would be something like:

A,B,0.98
A,C,0.9
C,R,-0.8
T,Z,0.5


推荐答案

这是我能想到的许多方法之一去做这个。我使用了reshape软件包,因为 melt()语法很容易记住,但是 melt()命令可以很容易地用基本的R命令完成:

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))

这篇关于将相关表显示为降序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆