通过特殊条件比较来自第二矩阵的所有行的第一矩阵的每一行,并将结果保存在矩阵中

时间:2017-08-19 22:42:58

标签: r

我有两个矩阵a和b,我试图将矩阵b的每一行与矩阵a的所有行进行比较。标准是:if(b!= 0和a!= 0)b的总和行并将结果除以b的总和与条件(如果b> 0或a> 0)  示例结果矩阵的第一个元素  r(b,a)=(a2 + a4 + a5)/(a1 + a2 + a4 + a5 + a6)= 15/27

step 1  compare the first row of b over first row of matrix a
first row of b (0,3,5,7,0,0,0)
first row of a (5,3,5,7,7,0,0)
under condition if( value of b not equal 0 and value a not equal 0) 
sum values of b that satisfied condition.   5+3+7 = 15
 step 2  compare the first row of b over first row of matrix a
first row of b (0,3,5,7,0,0,0)
first row of a (5,3,5,7,7,0,0)
under condition if( value of b greater than 0 or value a greater than 0) 
sum values of b that satisfied condition.   5+3+5+7+7 = 27

 another example 10/32
step 1  compare the first row of b over second row of matrix a
first row of  b (0,3,5,7,0,0,0)
second row of a (5,3,0,7,7,0,5)
under condition if( value of b not equal 0 and value a not equal 0)
 sum values of b that satisfied condition.  3+7 = 10  
step 2  compare the first row of b over second row of matrix a
first row of  b (0,3,5,7,0,0,0)
second row of a (5,3,0,7,7,0,5)
under condition if( value of b greater than 0 or value a greater than 0) 
sum values of b that satisfied condition.   5+3+5+7+7+5 = 32

a <-t(matrix(c(5,3,5,7,7,0,0,
               5,3,0,7,7,0,5,
               5,0,5,7,7,0,5,
               0,3,5,7,7,0,5,
               5,0,5,7,7,3,0,
               5,0,0,7,7,3,5,
               0,0,5,7,7,3,5),
               nrow=7,ncol=7))

b <-t(matrix(c(0,3,5,7,0,0,0,
               5,3,5,7,7,0,5,
               0,3,5,0,0,0,0,
               5,3,0,0,0,0,0,
               5,0,5,0,0,3,0,
               0,3,5,0,7,0,0,
               5,3,5,0,0,0,5),
               nrow=7,ncol=7))



result matrix 
       [,1]  [,2]   [,3]  [,4]  [,5]   [,6]   [,7]
[1,]  15/27  27/32  8/27  8/27  10/30  15/27  13/32
[2,]  10/32  27/32  3/32  8/27  5/35   10/32  13/32
[3,]  12/32  29/32  5/32  5/32  10/32  12/32  15/32
[4,]  15/27  27/32  8/27  3/32  5/35   15/27  13/32
[5,]  12/30  24/35  5/30  5/30  13/27  12/30  10/35
[6,]   7/35  24/35    0   5/30  8/32    7/35  10/35
[7,]  12/30  24/35  5/30    0   8/32   12/30  10/35

1 个答案:

答案 0 :(得分:1)

为了能够做到这一点,我们可以使用嵌套的apply来比较一个矩阵与另一个矩阵的行。

fun=function(x,y) {y[y==0]=x[y==0];sum(y)}
 t(apply(a,1,function(x) apply(b,1,function(y) sum(y[x!=0 &y!=0])/fun(x,y) )))
           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
 [1,] 0.5555556 0.8437500 0.2962963 0.2962963 0.3333333 0.5555556 0.4062500
 [2,] 0.3125000 0.8437500 0.0937500 0.2962963 0.1428571 0.3125000 0.4062500
 [3,] 0.3750000 0.9062500 0.1562500 0.1562500 0.3125000 0.3750000 0.4687500
 [4,] 0.5555556 0.8437500 0.2962963 0.0937500 0.1428571 0.5555556 0.4062500
 [5,] 0.4000000 0.6857143 0.1666667 0.1666667 0.4814815 0.4000000 0.2857143
 [6,] 0.2000000 0.6857143 0.0000000 0.1666667 0.2500000 0.2000000 0.2857143
 [7,] 0.4000000 0.6857143 0.1666667 0.0000000 0.2500000 0.4000000 0.2857143