简体   繁体   中英

Calculating the correlation between various columns of a matrix in R

I have the following matrix mat in R:

      x  y  z
rowA -1  1  2
rowB -1 -2 -1
rowC  2  1 -1

How do I calculate the correlation between various columns of the matrix (say, corr(x, y) , corr(y, z) , corr(x, z) ), rather than separating the columns into vectors?

you can do:

#gives pairwise
COR = cor(M)
# to get 1 vs 2, 1 vs 3 and 2 vs 3
COR[upper.tri(COR)]

We can use combn to create combination of column names taking 2 at a time, subset the combination from the matrix and then calculate the correlation between them.

combn(colnames(mat), 2, function(x) cor(mat[, x[1]], mat[, x[2]]))
#[1]  0.5 -0.5  0.5

data

mat <- structure(c(-1L, -1L, 2L, 1L, -2L, 1L, 2L, -1L, -1L), .Dim = c(3L, 
3L), .Dimnames = list(c("rowA", "rowB", "rowC"), c("x", "y", "z")))

Base R:

cor_df <- data.frame(vars = row.names(cor(mat)), cor(mat), row.names = NULL)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM