当在具有大量变量的时间序列上运行cor()时,我得到一个表,其中每个变量都有一行和一列,显示它们之间的相关性.
如何将此表视为从最相关到最不相关的列表(消除所有NA结果和映射回自身的结果(即A与A的相关性)).我还想将反(负)结果计为绝对值,但仍将其显示为负值.
所以期望的输出将是这样的:
A,B,0.98
A,C,0.9
C,R,-0.8
T,Z,0.5
Run Code Online (Sandbox Code Playgroud)
JD *_*ong 13
这是我能想到的很多方法之一.我使用了reshape包,因为melt()我melt()很容易记住语法,但是使用基本R命令可以很容易地完成命令:
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))
Run Code Online (Sandbox Code Playgroud)
Aar*_*ica 10
使用基数R(其中cors是相关矩阵):
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),]
Run Code Online (Sandbox Code Playgroud)