How can I create a correlation matrix in R?

后端 未结 5 785
情深已故
情深已故 2020-11-27 10:24

I have 92 set of data of same type.

I want to make a correlation matrix for any two combination possible.

i.e. I want a matrix of 92 x92.

such that e

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 10:54

    The cor function will use the columns of the matrix in the calculation of correlation. So, the number of rows must be the same between your matrix x and matrix y. Ex.:

    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

    Edit:

    Here is an example of custom row and column labels on a correlation matrix calculated with a single matrix:

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

提交回复
热议问题