Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
计算R中矩阵各列之间的相关性_R_Correlation - Fatal编程技术网

计算R中矩阵各列之间的相关性

计算R中矩阵各列之间的相关性,r,correlation,R,Correlation,我在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]

我在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")))
mat您可以执行以下操作:

#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)
cor_df
cor(mat)
应该可以正常工作。