A quick way to do row repeat and col repeat (rep.row, rep.col)

September 2, 2011
By

(This article was first published on R HEAD, and kindly contributed to R-bloggers)

Today I worked on a simulation program which require me to create a matrix by repeating the vector n times (both by row and by col).

Even the task is extremely simple and only take 1 line to finish(10sec), I have to think about should the argument in rep be each or times and should the argument in matrix is nrow or ncol. It distracted me from the original task i am working on.

Just now, I wrote a function rep.row and rep.col to do what I really want to do. Next time, i don’t have to worry about how to use the matrix and rep command to repeat an vector to form a matrix!

Code

rep.row<-function(x,n){
   matrix(rep(x,each=n),nrow=n)
}
rep.col<-function(x,n){
   matrix(rep(x,each=n), ncol=n, byrow=TRUE)
}

x is the vector to be repeated and n is the number of replication. Example:

> rep.row(1:3,5)
      [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    2    3
[3,]    1    2    3
[4,]    1    2    3
[5,]    1    2    3
> rep.col(1:3,5)
      [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    2    2    3
[2,]    1    1    2    3    3
[3,]    1    2    2    3    3

I am sure it should appear in some packages, but it would be faster for me to write it out than find it out!


To leave a comment for the author, please follow the link and comment on his blog: R HEAD.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.