Repeat elements of vector in R

Assuming you a is a vector, sapply will create a matrix that just needs to be collapsed back into a vector:

a<-c("a","b","c")
b<-3 # Or some other number
a<-sapply(a, function (x) rep(x,b))
a<-as.vector(a)

Should create the following output:

"a" "a" "a" "b" "b" "b" "c" "c" "c"

a is not a vector, you have to split the string into single characters, e.g.

R> paste(rep(strsplit("abc","")[[1]], each=2), collapse="")
[1] "aabbcc"

Tags:

R

Plyr