FR_
FR_

Reputation: 147

Concatenate each row of a matrix with each element of another matrix R

I want to concatenate each row of a matrix (say m1) with each element of another matrix (m2). Here follows an exmple:

m1 <- t(combn(4,2))
m2 <- matrix(NA,nrow(m1),2)
for(i in 1:nrow(m1)){
    m2[i,] <- seq(1,4,1)[-c(m1[i,])] 
   }
> m1
     [,1] [,2]
[1,]    1    2
[2,]    1    3
[3,]    1    4
[4,]    2    3
[5,]    2    4
[6,]    3    4

> m2
     [,1] [,2]
[1,]    3    4
[2,]    2    4
[3,]    2    3
[4,]    1    4
[5,]    1    3
[6,]    1    2

The matrix that I want should be like this:

> m3
      [,1] [,2] [,3]
 [1,]    1    2    3
 [2,]    1    2    4
 [3,]    1    3    2
 [4,]    1    3    4
 [5,]    1    4    2
 [6,]    1    4    3
 [7,]    2    3    1
 [8,]    2    3    4
 [9,]    2    4    1
[10,]    2    4    3
[11,]    3    4    1
[12,]    3    4    2

What is the best practice in this case?

Upvotes: 2

Views: 130

Answers (1)

akrun
akrun

Reputation: 887163

As per the expected output, the logic seems to be that we are expanding the rows of the first dataset by also includng the second dataset, so the number of rows should be double as of the first. In the current approach, we used rep to expand the rows and then cbind with the vector created from the second matrix

cbind(m1[rep(1:nrow(m1), each = 2),], c(t(m2)))
#       [,1] [,2] [,3]
# [1,]    1    2    3
# [2,]    1    2    4
# [3,]    1    3    2
# [4,]    1    3    4
# [5,]    1    4    2
# [6,]    1    4    3
# [7,]    2    3    1
# [8,]    2    3    4
# [9,]    2    4    1
#[10,]    2    4    3
#[11,]    3    4    1
#[12,]    3    4    2

Upvotes: 3

Related Questions