Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Matrix row by row alternating

Tags:

r

matrix

rbind

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.

like image 922
CoDa Avatar asked Nov 21 '25 15:11

CoDa


2 Answers

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)))
like image 87
Maël Avatar answered Nov 24 '25 06:11

Maël


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
like image 42
Wimpel Avatar answered Nov 24 '25 06:11

Wimpel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!