计算R中矩阵各列之间的相关性
Calculating the correlation between various columns of a matrix in R
我在 R 中有以下矩阵 mat
:
x y z
rowA -1 1 2
rowB -1 -2 -1
rowC 2 1 -1
如何计算矩阵各列之间的相关性(例如,corr(x, y)
、corr(y, z)
、corr(x, z)
),而不是将列分成向量?
我们可以使用combn
创建一次取2个列名的组合,从矩阵中对组合进行子集化,然后计算它们之间的相关性。
combn(colnames(mat), 2, function(x) cor(mat[, x[1]], mat[, x[2]]))
#[1] 0.5 -0.5 0.5
数据
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")))
你可以做到:
#gives pairwise
COR = cor(M)
# to get 1 vs 2, 1 vs 3 and 2 vs 3
COR[upper.tri(COR)]
基数 R:
cor_df <- data.frame(vars = row.names(cor(mat)), cor(mat), row.names = NULL)
我在 R 中有以下矩阵 mat
:
x y z
rowA -1 1 2
rowB -1 -2 -1
rowC 2 1 -1
如何计算矩阵各列之间的相关性(例如,corr(x, y)
、corr(y, z)
、corr(x, z)
),而不是将列分成向量?
我们可以使用combn
创建一次取2个列名的组合,从矩阵中对组合进行子集化,然后计算它们之间的相关性。
combn(colnames(mat), 2, function(x) cor(mat[, x[1]], mat[, x[2]]))
#[1] 0.5 -0.5 0.5
数据
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")))
你可以做到:
#gives pairwise
COR = cor(M)
# to get 1 vs 2, 1 vs 3 and 2 vs 3
COR[upper.tri(COR)]
基数 R:
cor_df <- data.frame(vars = row.names(cor(mat)), cor(mat), row.names = NULL)