如何在R中创建相关矩阵?

Swa*_*kle 84 visualization r matrix correlation

我有92组相同类型的数据.

我想为任意两种组合制作相关矩阵.

即我想要一个92 x92的矩阵.

元素(ci,cj)应该是ci和cj之间的相关性.

我怎么做?

Man*_*món 101

一个例子,

 d <- data.frame(x1=rnorm(10),
                 x2=rnorm(10),
                 x3=rnorm(10))
cor(d) # get correlations (returns matrix)
Run Code Online (Sandbox Code Playgroud)


Jot*_* eN 71

你可以使用'corrplot'包.

d <- data.frame(x1=rnorm(10),
                 x2=rnorm(10),
                 x3=rnorm(10))
M <- cor(d) # get correlations

library('corrplot') #package corrplot
corrplot(M, method = "circle") #plot matrix
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这里更多信息:http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html


Mar*_*box 16

COR函数将使用矩阵的列中的相关性的计算.因此,矩阵x和矩阵y之间的行数必须相同.例:

set.seed(1)
x <- matrix(rnorm(20), nrow=5, ncol=4)
y <- matrix(rnorm(15), nrow=5, ncol=3)
COR <- cor(x,y)
COR
image(x=seq(dim(x)[2]), y=seq(dim(y)[2]), z=COR, xlab="x column", ylab="y column")
text(expand.grid(x=seq(dim(x)[2]), y=seq(dim(y)[2])), labels=round(c(COR),2))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

编辑:

以下是使用单个矩阵计算的相关矩阵上的自定义行和列标签的示例:

png("corplot.png", width=5, height=5, units="in", res=200)
op <- par(mar=c(6,6,1,1), ps=10)
COR <- cor(iris[,1:4])
image(x=seq(nrow(COR)), y=seq(ncol(COR)), z=cor(iris[,1:4]), axes=F, xlab="", ylab="")
text(expand.grid(x=seq(dim(COR)[1]), y=seq(dim(COR)[2])), labels=round(c(COR),2))
box()
axis(1, at=seq(nrow(COR)), labels = rownames(COR), las=2)
axis(2, at=seq(ncol(COR)), labels = colnames(COR), las=1)
par(op)
dev.off()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


epo*_*po3 14

看看qtlcharts.它允许您创建交互式相关矩阵:

library(qtlcharts)
data(iris)
iris$Species <- NULL
iplotCorr(iris, reorder=TRUE)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

当您关联更多变量时,它会更令人印象深刻,例如包的插图: 在此输入图像描述