[英]how do i calculate correlation between corresponding columns of two matrices and not getting other correlations as output
我有這些數據
> a
a b c
1 1 -1 4
2 2 -2 6
3 3 -3 9
4 4 -4 12
5 5 -5 6
> b
d e f
1 6 -5 7
2 7 -4 4
3 8 -3 3
4 9 -2 3
5 10 -1 9
> cor(a,b)
d e f
a 1.0000000 1.0000000 0.1767767
b -1.0000000 -1.000000 -0.1767767
c 0.5050763 0.5050763 -0.6964286
我想要的結果只是:
cor(a,d) = 1
cor(b,e) = -1
cor(c,f) = -0.6964286
上面的第一個答案計算所有成對相關性,除非矩陣很大,否則這很好,而第二個答案不起作用。 據我所知,必須直接進行高效計算,例如從 arrayMagic Bioconductor package 借來的代碼,對於大型矩陣有效:
> colCors = function(x, y) {
+ sqr = function(x) x*x
+ if(!is.matrix(x)||!is.matrix(y)||any(dim(x)!=dim(y)))
+ stop("Please supply two matrices of equal size.")
+ x = sweep(x, 2, colMeans(x))
+ y = sweep(y, 2, colMeans(y))
+ cor = colSums(x*y) / sqrt(colSums(sqr(x))*colSums(sqr(y)))
+ return(cor)
+ }
> set.seed(1)
> a=matrix(rnorm(15),nrow=5)
> b=matrix(rnorm(15),nrow=5)
> diag(cor(a,b))
[1] 0.2491625 -0.5313192 0.5594564
> mapply(cor,a,b)
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
> colCors(a,b)
[1] 0.2491625 -0.5313192 0.5594564
我個人可能只會使用diag
:
> diag(cor(a,b))
[1] 1.0000000 -1.0000000 -0.6964286
但你也可以使用mapply
:
> mapply(cor,a,b)
a b c
1.0000000 -1.0000000 -0.6964286
mapply
適用於數據框,但不適用於矩陣。 這是因為在數據幀中,每一列都是一個元素,而在矩陣中,每個條目都是一個元素。
在上面的答案中, mapply(cor,as.data.frame(a),as.data.frame(b))
工作得很好。
set.seed(1)
a=matrix(rnorm(15),nrow=5)
b=matrix(rnorm(15),nrow=5)
diag(cor(a,b))
[1] 0.2491625 -0.5313192 0.5594564
mapply(cor,as.data.frame(a),as.data.frame(b))
V1 V2 V3
0.2491625 -0.5313192 0.5594564
這對於大型矩陣更有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.