Multiplying two sets of vectors in R

Suppose I have two matrices A and B:

 A:      A1    A2        B:      B1   B2
   ROW1  V1    V2          ROW1  V3   V4
   ROW2  V5    V6          ROW2  V7   V8

I want to get the resulting matrix R, which will include the products of each pair of two columns of the matrix:

 R:      A1_B1  A1_B2  A2_B1  A2_B2
   ROW1  V1*V3  V1*V4  V2*V3  V2*V4
   ROW2  V5*V7  V5*V8  V6*V7  V6*V8

There may be a loop structure, but I'm wondering if there are more affordable options.

+3
source share
3 answers

You can use apply:

A <- matrix(1:4,2,2)
#     [,1] [,2]
# [1,]    1    3
# [2,]    2    4
B <- A * 10
#      [,1] [,2]
# [1,]   10   30
# [2,]   20   40

matrix(apply(A, 2, "*", B), nrow = nrow(A))
#      [,1] [,2] [,3] [,4]
# [1,]   10   30   30   90
# [2,]   40   80   80  160

ADDITION Antti:

It works great. In the end, I needed it for management data.frame. To apply meaningful column names for this data.frame, I did the following:

  • make this matrix data.frame:

    R <- as.data.frame(R)
    
  • make column name vectors in A and B

    Acol <- grep("A", names(data.frame(A)), value = T) 
    Bcol <- grep("B", names(data.frame(B)), value = T) 
    
  • Then rename the columns to R:

    colnames(R) <- outer(Acol, Bcol, paste, sep = ".")
    
+5
source

, :

> A=matrix(c(1,5,2,6),2,2)
> B=matrix(c(3,7,4,8),2,2)
> A
     [,1] [,2]
[1,]    1    2
[2,]    5    6
> B
     [,1] [,2]
[1,]    3    4
[2,]    7    8

A B. : A1, A1, A2, A2 () B1 B2 B1 B2 - expand.grid:

> cols = as.matrix(expand.grid(1:2,1:2))
> cols
     Var1 Var2
[1,]    1    1
[2,]    2    1
[3,]    1    2
[4,]    2    2

A B ( ):

> A[,cols[,2]] * B[,cols[,1]]
     [,1] [,2] [,3] [,4]
[1,]    3    4    6    8
[2,]   35   40   42   48

[ , A B V-, , V6 * V8 6 * 8]

0
A <- matrix(1:4,2,2)
B <- A * 10

cbind(A[,1]*B, A[,2]*B)

     [,1] [,2] [,3] [,4]
[1,]   10   30   30   90
[2,]   40   80   80  160
0
source

All Articles