Concatenate each row of a matrix with each element of another matrix R -
i want concatenate each row of matrix (say m1) each element of matrix (m2). here follows 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 want should 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 best practice in case?
as per expected output, logic seems expanding rows of first dataset includng second dataset, number of rows should double of first. in current approach, used rep
expand rows , cbind
vector
created 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
Comments
Post a Comment