Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat elements of vector in R

Tags:

r

plyr

I'm trying to repeat the elements of vector a, b number of times. That is, a="abc" should be "aabbcc" if y = 2.

Why doesn't either of the following code examples work?

sapply(a, function (x) rep(x,b))

and from the plyr package,

aaply(a, function (x) rep(x,b))

I know I'm missing something very obvious ...

like image 266
bshor Avatar asked May 12 '10 19:05

bshor


2 Answers

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"
like image 144
rcs Avatar answered Oct 23 '22 22:10

rcs


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"
like image 25
patrick95350 Avatar answered Oct 23 '22 22:10

patrick95350