[R] binding rows from different matrices

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Jun 29 17:35:46 CEST 2004


You can almost always index in such problems: here is one way.

rbind(veca,vecb,vecc)[matrix(1:15, 3, byrow=T), ]

Take it apart of see how it works, if it is not immediately obvious.

On Tue, 29 Jun 2004, Stephane DRAY wrote:

> Hello list,
> I have 3 matrices with same dimension :
>  > veca=matrix(1:25,5,5)
>  > vecb=matrix(letters[1:25],5,5)
>  > vecc=matrix(LETTERS[1:25],5,5)
> 
> I would like to obtain a new matrix composed by alternating rows of these 
> different matrices (row 1 of mat 1, row 1 of mat 2, row 1 of mat 3, row 2 
> of mat 1.....)
> 
> I have found a solution to do it but it is not very pretty and I wonder if 
> I can do it in an other way (perhaps with apply ) ?
> 
>  > res=matrix(0,1,5)
>  > for(i in 1:5)
> + res=rbind(res,veca[i,],vecb[i,],vecc[i,])
>  > res=res[-1,]
>  > res
>        [,1] [,2] [,3] [,4] [,5]
>   [1,] "1"  "6"  "11" "16" "21"
>   [2,] "a"  "f"  "k"  "p"  "u"
>   [3,] "A"  "F"  "K"  "P"  "U"
>   [4,] "2"  "7"  "12" "17" "22"
>   [5,] "b"  "g"  "l"  "q"  "v"
>   [6,] "B"  "G"  "L"  "Q"  "V"
>   [7,] "3"  "8"  "13" "18" "23"
>   [8,] "c"  "h"  "m"  "r"  "w"
>   [9,] "C"  "H"  "M"  "R"  "W"
> [10,] "4"  "9"  "14" "19" "24"
> [11,] "d"  "i"  "n"  "s"  "x"
> [12,] "D"  "I"  "N"  "S"  "X"
> [13,] "5"  "10" "15" "20" "25"
> [14,] "e"  "j"  "o"  "t"  "y"
> [15,] "E"  "J"  "O"  "T"  "Y"

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list