Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining 3 arrays by row number

Tags:

arrays

r

Is there a way to combine three arrays in R so that the first row of the first array is followed by the first row of the second array and that is followed by the third row of the third array? So, if I ran the following code:

> number1<-rbind(rep("A",3), rep("B",3), rep("C",3))
> number1
     [,1] [,2] [,3]
[1,] "A"  "A"  "A" 
[2,] "B"  "B"  "B" 
[3,] "C"  "C"  "C" 
> number2<-rbind(rep(1,3), rep(2,3), rep(3,3))
> number2
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3
> number3<-rbind(rep("X",3), rep("Y",3), rep("Z",3))
> number3
     [,1] [,2] [,3]
[1,] "X"  "X"  "X" 
[2,] "Y"  "Y"  "Y" 
[3,] "Z"  "Z"  "Z"

The result would look like this:

      [,1] [,2] [,3]
 [1,] "A"  "A"  "A" 
 [2,] "1"  "1"  "1" 
 [3,] "X"  "X"  "X" 
 [4,] "B"  "B"  "B" 
 [5,] "2"  "2"  "2" 
 [6,] "Y"  "Y"  "Y" 
 [7,] "C"  "C"  "C" 
 [8,] "3"  "3"  "3" 
 [9,] "Z"  "Z"  "Z"

I have tried melt but I can't get it to work.

like image 682
user3390169 Avatar asked Aug 26 '15 18:08

user3390169


1 Answers

You could try this:

> matrix(t(cbind(number1,number2,number3)),ncol=3, byrow=T)
#      [,1] [,2] [,3]
# [1,] "A"  "A"  "A" 
# [2,] "1"  "1"  "1" 
# [3,] "X"  "X"  "X" 
# [4,] "B"  "B"  "B" 
# [5,] "2"  "2"  "2" 
# [6,] "Y"  "Y"  "Y" 
# [7,] "C"  "C"  "C" 
# [8,] "3"  "3"  "3" 
# [9,] "Z"  "Z"  "Z" 
like image 154
RHertel Avatar answered Sep 21 '22 21:09

RHertel