當在具有大量變量的時間序列上運行cor()時,我得到一個表格,每個變量都有一行和一列,顯示它們之間的相關性。按降序列表顯示相關表
如何查看此表格作爲從最相關到最不相關的列表(消除所有NA結果和映射回自己的結果(即A到A的相關性))。我也想把倒數(負數)的結果作爲絕對值,但仍然顯示爲負值。
因此所需的輸出會是這樣的:
A,B,0.98
A,C,0.9
C,R,-0.8
T,Z,0.5
當在具有大量變量的時間序列上運行cor()時,我得到一個表格,每個變量都有一行和一列,顯示它們之間的相關性。按降序列表顯示相關表
如何查看此表格作爲從最相關到最不相關的列表(消除所有NA結果和映射回自己的結果(即A到A的相關性))。我也想把倒數(負數)的結果作爲絕對值,但仍然顯示爲負值。
因此所需的輸出會是這樣的:
A,B,0.98
A,C,0.9
C,R,-0.8
T,Z,0.5
這裏有很多方面我能想到這樣做的。我使用的重塑包,因爲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))
使用基礎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),]
用您的關聯調用替換...
。
library(reshape)
x <- subset(melt(cor(...)), value != 1 | value != NA)
x <- x[with(x, order(-abs(x$value))),]
如果你要在你的相關性有很多NA的,也許嘗試使用您的相關調用use="complete.obs"
說法。