[英]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)
)之間的相關性,而不是將列分成向量?
你可以做:
#gives pairwise
COR = cor(M)
# to get 1 vs 2, 1 vs 3 and 2 vs 3
COR[upper.tri(COR)]
我們可以使用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")))
底座 R:
cor_df <- data.frame(vars = row.names(cor(mat)), cor(mat), row.names = NULL)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.