Home > other >  Combining Matrix row by row alternating
Combining Matrix row by row alternating

Time:10-08

Given two matrices:

test1 <- matrix(1:5,ncol=1)

test2 <- matrix(6:10,ncol=1)

I would like to combine them into one single matrix row by row in an alternating way, meaning:

expected_output <- matrix(c(1,6,2,7,3,8,4,9,5,10),ncol=1)

or more visual:

enter image description here

I already created an empty matrix double the length of test1, but i am lacking how to add row by row each value. rbind() is only adding the whole matrix.

CodePudding user response:

With c t cbind

c(t(cbind(test1, test2)))
#[1]  1  6  2  7  3  8  4  9  5 10

in a matrix form:

matrix(t(cbind(test1, test2)))

CodePudding user response:

c(mapply(append, test1, test2))
[1]  1  6  2  7  3  8  4  9  5 10

if matrix outut is needed, use

as.matrix(c(mapply(append, test1, test2)), ncol = 1)
      [,1]
 [1,]    1
 [2,]    6
 [3,]    2
 [4,]    7
 [5,]    3
 [6,]    8
 [7,]    4
 [8,]    9
 [9,]    5
[10,]   10

CodePudding user response:

This does what you ask assuming your matrices have the indicated number of rows. You can adjust the grid accordingly.

test1 <- matrix(1:5,ncol=1)
test2 <- matrix(6:10,ncol=1)
expected_output <- matrix(c(1,6,2,7,3,8,4,9,5,10),ncol=1)

out <- matrix(NA, nrow = nrow(test1)   nrow(test2), ncol = 1)
grid1 <- seq(1, 9, by = 2)
grid2 <- seq(2, 10, by = 2)
out[ grid1, ] = test1
out[ grid2, ] = test2
out
#>       [,1]
#>  [1,]    1
#>  [2,]    6
#>  [3,]    2
#>  [4,]    7
#>  [5,]    3
#>  [6,]    8
#>  [7,]    4
#>  [8,]    9
#>  [9,]    5
#> [10,]   10

Created on 2022-10-07 by the reprex package (v2.0.1)

CodePudding user response:

You can use order like below (assuminge test1 and test2 are of the same length always)

> c(test1, test2)[order(rep(seq_along(test1), 2))]
 [1]  1  6  2  7  3  8  4  9  5 10

CodePudding user response:

Use the odd and even numbers sequences, respectively 2*n - 1 and 2*n to create index vectors and assign the test* matrices to a results matrix rowws.

test1 <- matrix(1:5,ncol=1)
test2 <- matrix(6:10,ncol=1)

n1 <- nrow(test1)
n2 <- nrow(test2)

expected_output <- matrix(nrow =  n1   n2, ncol = 1)

i1 <- 2*seq_len(n1) - 1
i2 <- 2*seq_len(n2)
expected_output[i1,] <- test1
expected_output[i2,] <- test2

expected_output
#>       [,1]
#>  [1,]    1
#>  [2,]    6
#>  [3,]    2
#>  [4,]    7
#>  [5,]    3
#>  [6,]    8
#>  [7,]    4
#>  [8,]    9
#>  [9,]    5
#> [10,]   10

Created on 2022-10-07 with reprex v2.0.2

CodePudding user response:

Another option. First add an id to your input matrices.

test1 <- matrix(1:5,ncol=1) |> 
  cbind(id = 1:5)

test2 <- matrix(6:10,ncol=1) |> 
  cbind(id = 1:5)

Then combine.

test1 |> 
  rbind(test2) |> 
  (\(x) (x[order(x[,2], decreasing = FALSE), 1]))() |> 
  as.matrix()

which gives:

      [,1]
 [1,]    1
 [2,]    6
 [3,]    2
 [4,]    7
 [5,]    3
 [6,]    8
 [7,]    4
 [8,]    9
 [9,]    5
[10,]   10
  • Related