首页 文章

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

提问于
浏览
77

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

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

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

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

我怎么做?

5 回答

  • 1

    一个例子,

    d <- data.frame(x1=rnorm(10),
                     x2=rnorm(10),
                     x3=rnorm(10))
    cor(d) # get correlations (returns matrix)
    
  • 15

    你可以使用'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
    

    enter image description here

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

  • 92

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

    enter image description here

    编辑:

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

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

    enter image description here

  • 69

    看看qtlcharts . 它允许您创建 interactive 相关矩阵:

    library(qtlcharts)
    data(iris)
    iris$Species <- NULL
    iplotCorr(iris, reorder=TRUE)
    

    enter image description here

    它's more impressive when you correlate more variables, like in the package'的小插图:
    enter image description here

  • 13

    还有其他方法可以实现这一点:(Plot correlation matrix into a graph),但我喜欢你的版本与框中的相关性 . 有没有办法将变量名称添加到x和y列而不仅仅是那些索引号?对我来说,这将使这成为一个完美的解决方案 . 谢谢!

    编辑:我试图通过[Marc in the box]对帖子发表评论,但我显然不知道自己在做什么 . 但是,我确实设法自己回答了这个问题 .

    如果d是矩阵(或原始数据框)并且列名是您想要的,那么以下工作:

    axis(1, 1:dim(d)[2], colnames(d), las=2)
    axis(2, 1:dim(d)[2], colnames(d), las=2)
    

    las = 0会将名称翻转回正常位置,我的名字很长,所以我使用las = 2使它们垂直于轴 .

    edit2:抑制image()函数在网格上打印数字(否则它们与变量标签重叠),添加xaxt ='n',例如:

    image(x=seq(dim(x)[2]), y=seq(dim(y)[2]), z=COR, col=rev(heat.colors(20)), xlab="x column", ylab="y column", xaxt='n')
    

相关问题