收缩(简化)矩阵

时间:2015-04-27 17:20:43

标签: r

如何缩小R中的矩阵?

我有随机数矩阵

a = 5
myMatrix <- matrix(rnorm(a*a),ncol=a)
diag(myMatrix) <- 0

myMatrix
        [,1]       [,2]       [,3]       [,4]       [,5]
[1,]  0.00000000 -0.6610853 -0.7072980  1.1899888  0.8607588
[2,] -0.68123068  0.0000000  0.6870920 -1.1284451 -1.6981509
[3,]  0.88768478  1.3605526  0.0000000 -0.4632346  1.2166078
[4,]  0.01453834  2.1967867  0.3330623  0.0000000 -0.6867518
[5,] -0.09157931 -0.7998323 -0.8322993  1.4207877  0.0000000

如何缩小(简化)此矩阵。例如

myMatrix[1,2]
[1] -0.6610853
myMatrix[2,1]
[1] -0.6812307

所以这对被简化为一个数字(例如,myMatix[2,1] - myMatix[1,2])。如何为所有对(如1,3; 1,4)执行此操作?

我不是来自数学背景,我不知道具体的术语,但我希望R中有一个简单的解决方案,我想要的。

PS。这不是作业。

2 个答案:

答案 0 :(得分:1)

以下是使用combn()然后sapply()的一种可能解决方案:

a <- 5;
m <- matrix(c(0,-0.68123068,0.88768478,0.01453834,-0.09157931,-0.6610853,0,1.3605526,2.1967867,-0.7998323,-0.707298,0.687092,0,0.3330623,-0.8322993,1.1899888,-1.1284451,-0.4632346,0,1.4207877,0.8607588,-1.6981509,1.2166078,-0.6867518,0),a);
c <- combn(a,2);
sapply(1:ncol(c),function(x) m[c[2,x],c[1,x]]-m[c[1,x],c[2,x]]);
##  [1] -0.02014538  1.59498278 -1.17545046 -0.95233811  0.67346060  3.32523180  0.89831860  0.79629690 -2.04890710  2.10753950

修改:实际上,这是一种更好的矢量化方法,使用上面的c

m[c[2,]+(c[1,]-1)*a]-m[c[1,]+(c[2,]-1)*a];
##  [1] -0.02014538  1.59498278 -1.17545046 -0.95233811  0.67346060  3.32523180  0.89831860  0.79629690 -2.04890710  2.10753950

答案 1 :(得分:0)

你可以尝试

myMatrix[lower.tri(myMatrix)] -  t(myMatrix)[lower.tri(t(myMatrix))]
#[1] -0.02014538  1.59498278 -1.17545046 -0.95233811  0.67346060  3.32523180
#[7]  0.89831860  0.79629690 -2.04890710  2.10753950

或者它可以写成

(myMatrix-t(myMatrix))[lower.tri(myMatrix)]
#[1] -0.02014538  1.59498278 -1.17545046 -0.95233811  0.67346060  3.32523180
#[7]  0.89831860  0.79629690 -2.04890710  2.10753950

数据

myMatrix <- structure(c(0, -0.68123068, 0.88768478, 0.01453834, 
-0.09157931, 
-0.6610853, 0, 1.3605526, 2.1967867, -0.7998323, -0.707298, 0.687092, 
0, 0.3330623, -0.8322993, 1.1899888, -1.1284451, -0.4632346, 
0, 1.4207877, 0.8607588, -1.6981509, 1.2166078, -0.6867518, 0
), .Dim = c(5L, 5L))