r 将每个矩阵行与列中的元素相乘

r multiplying each matrix row with elements from column

如果这些是我的 nx6 矩阵的前 6 行

  x1    x2   x3  x4  x5  a1
   1    30    3  43   0  0.20
   3    40    2  35   0  0.21
   3    50    7  72   0  0.75
   4    40   58  63  10  0.55
   1    20   19  61  10  0.43
   4    20    5  49   0  0.62

目标是根据这个逻辑创建一个newnx5矩阵。 X1-X5 中的每一行都应像这样乘以 a1 中的标量值

a2
[1,30,3,43,0]*0.20 + [1,30,3,43,0]*0.21 + [1,30,3,43,0]*0.75 + [1,30,3,43,0]*0.55 + [1,30,3,43,0]*0.43 + [1,30,3,43,0]*0.62
                     [3,40,2,35,0]*0.21 + [3,40,2,35,0]*0.75 + [3,40,2,35,0]*0.55 + [3,40,2,35,0]*0.43 + [3,40,2,35,0]*0.62
                                          [3,50,7,72,0]*0.75 + [3,50,7,72,0]*0.55 + [3,50,7,72,0]*0.43 + [3,50,7,72,0]*0.62
                                                               [4,40,58,63,10]*0.55 + [4,40,58,63,10]*0.43 + [4,40,58,63,10]*0.62
                                                                          [1,20,19,61,10]*0.43 + [1,20,19,61,10]*0.62
                                                                                                         [4,20,5,49,0]*0.62

最后得到的是下面的nx5矩阵

 2.76     82.8   8.28    118.68    0
 7.68    102.4   5.12     89.6     0
 7.05    117.5  16.45    169.2     0
 6.4      64    92.8     100.8    16
 1.05     21    19.95     64.05   10.5
 2.48     12.4   3.1      30.38    0

对于完成此操作的任何指示表示赞赏。谢谢

我们可以使用 sapply 遍历行序列,然后在最后一列和其余列之间进行交叉运算,同时我们使用从该行到最后一列的元素作为最后一列

t( sapply(seq_len(nrow(m1)), function(i) {
         x1 <-  m1[i:nrow(m1),6]
          x2 <- m1[i, -6]
          matrix(x2, length(x2), length(x1)) %*% x1 }))

数据

m1 <- structure(c(1, 3, 3, 4, 1, 4, 30, 40, 50, 40, 20, 20, 3, 2, 7, 
58, 19, 5, 43, 35, 72, 63, 61, 49, 0, 0, 0, 10, 10, 0, 0.2, 0.21, 
0.75, 0.55, 0.43, 0.62), .Dim = c(6L, 6L), .Dimnames = list(NULL, 
    c("x1", "x2", "x3", "x4", "x5", "a1")))