[R] rbind for matrices - rep argument

Ben Bolker bolker at ufl.edu
Wed Jan 7 17:20:49 CET 2009


Dimitris Rizopoulos <d.rizopoulos <at> erasmusmc.nl> writes:

> 
> you can use indexing, e.g.,
> 
> mat <- matrix(rnorm(20), 4, 5)
> 
> mat
> mat[rep(1:nrow(mat), 3), ]
> 
> I hope it helps.
> 
> Best,
> Dimitris

  or matrix trickery:

z <- as.data.frame(matrix(sample(1:9,20,replace=TRUE),nrow=4))
matrix(rep(as.matrix(z),3),ncol=ncol(z),byrow=TRUE)

  I do sometimes wish there were a more generic Rep() defined as

Rep <- function(x,n) {
  result <- list()
  for (i in 1:n) {
     result[[i]] <- x
  }
  result
}

then one could say do.call("rbind",Rep(x,3))




More information about the R-help mailing list