Search code examples
rmathdataframedplyrmultiplication

Data frame multiplication and storing in a other data frame using R


I have the following sample dataset of many rows and columns. I am trying to multiply each row of DF1 to each and every row of DF2. And the result of the multiplication to store in a different data frame. I tried using DF1 %*% DF2 but could not able to run successfully as matrix multiplication is not possible with this. Can anyone please help in solving this

DF1:

A   B   C   D   E   F   G
1   5   4   6   4   3   1
4   5   5   7   5   4   2
5   2   6   8   6   5   3
5   3   7   8   7   7   3
5   4   8   6   8   8   4
5   5   7   3   5   9   6

DF2:

A   B   C   D   E   F   G                   
1   0   0   0   1   0   0
0   0   1   0   0   0   0
1   0   0   0   0   0   1
0   0   0   1   0   1   0
1   0   0   1   0   0   1

OUTPUT:

T1  T2  T3  T4  T5  T6
5   9   11  12  10  10
4   5   6   7   7   7
2   6   8   8   11  11
9   11  13  15  14  12
8   13  16  16  15  14

Solution

  • We can try

    DF3 <- as.data.frame(t(as.matrix(DF1) %*% t(DF2)))
    DF3
    #   V1 V2 V3 V4 V5 V6
    #1  5  9 11 12 13 10
    #2  4  5  6  7  8  7
    #3  2  6  8  8  9 11
    #4  9 11 13 15 14 12
    #5  8 13 16 16 15 14