Home > Blockchain >  Using rbind on two matrices to match rows
Using rbind on two matrices to match rows

Time:12-08

I have two data frames, matrix A and matrix B, structured like

matrix A
       [,1] [,2]  [,3]  [,4] 
 [1,]   121  114   117   200 
 [2,]   312  215    78   211
 [3,]   413  121   719   117
 
matrix B
       [,1] [,2]  [,3]  [,4] 
 [1,]   120  119   112   220 
 [2,]     0    7     1     2
 [3,]   412  111   713   113
 

I want to create a new list of data frames with each sublist being the matches row values from both matrices. So for example, the first new data frame in the list would be

matrix C1
       [,1] [,2]  [,3]  [,4] 
 [1,]   121  114   117   200 
 [2,]     0    7     1     2

Row 1 in C1 is Row 1 from matrix A, Row 2 in this new matrix is Row 1 from matrix B. Matrix C2 would be Row 2 from matrix A and B, etc.

I know I have to use rbind() at one point, but I'm getting lost on how to get to my desired output?

CodePudding user response:

With BaseR,

lapply(1:nrow(matrixA), function(x) rbind(matrixA[x,],matrixB[x,]))

gives,

[[1]]
         [,1]     [,2]     [,3]
[1,] 52.81736 68.83760 92.26946
[2,] 49.17765 59.02276 15.89793

[[2]]
         [,1]     [,2]     [,3]
[1,] 48.21500 35.82741 11.52465
[2,] 33.05838 23.17105 70.05778

[[3]]
         [,1]     [,2]     [,3]
[1,] 52.93969 84.12350 21.44636
[2,] 47.69968 73.66894 27.14668

Fake Data:

    matrixA <- matrix(runif(9,1,100),3)
    matrixB <- matrix(runif(9,1,100),3)

CodePudding user response:

You can put them in an array and use aperm.

Starting data

matrixA <- matrix(runif(9,1,100),3)
matrixB <- matrix(runif(9,1,100),3)
list(matrixA, matrixB)    
#> [[1]]
#>           [,1]     [,2]     [,3]
#> [1,]  7.726875 88.77164 32.74513
#> [2,] 60.005675 26.94784 68.45881
#> [3,] 43.514952 94.43019 21.05740
#> 
#> [[2]]
#>          [,1]     [,2]      [,3]
#> [1,] 13.48753 65.43023 47.474468
#> [2,] 48.18658 25.19455 16.581541
#> [3,] 60.94665 58.46271  9.016365

Make an array and aperm

list(matrixA, matrixB) |>
  simplify2array() |>
  aperm()
#> , , 1
#> 
#>           [,1]     [,2]     [,3]
#> [1,]  7.726875 88.77164 32.74513
#> [2,] 13.487534 65.43023 47.47447
#> 
#> , , 2
#> 
#>          [,1]     [,2]     [,3]
#> [1,] 60.00567 26.94784 68.45881
#> [2,] 48.18658 25.19455 16.58154
#> 
#> , , 3
#> 
#>          [,1]     [,2]      [,3]
#> [1,] 43.51495 94.43019 21.057402
#> [2,] 60.94665 58.46271  9.016365

Created on 2021-12-07 by the reprex package (v2.0.1)

CodePudding user response:

Here is an example using row index:

# matrix1
M1 <- matrix(c(3:14), nrow = 4, byrow = TRUE)

# matrix2
M2 <- matrix(c(13:24), nrow = 4, byrow = TRUE)

M3 <- rbind(M1[1,], M2[2,])
M3
     [,1] [,2] [,3]
[1,]    3    4    5
[2,]   16   17   18
  • Related