Repeat elements of vector in R
Asked Answered
F

3

9

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 ...

Fireworks answered 12/5, 2010 at 19:7 Comment(0)
S
10

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"
Slideaction answered 12/5, 2010 at 22:19 Comment(1)
Forgot about collapsing it. This obviously works. Not sure why plyr's aaply doesn't. Oh well.Fireworks
S
17

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"
Sodium answered 12/5, 2010 at 19:17 Comment(2)
The "each=" argument to rep is notable, too. :-)Fosse
I made a mistake in my writeup of the question, a was indeed meant to be a vector, eg a=c("a","b","c"). If it weren't, your solution is obviously correct. Thanks!Fireworks
S
10

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"
Slideaction answered 12/5, 2010 at 22:19 Comment(1)
Forgot about collapsing it. This obviously works. Not sure why plyr's aaply doesn't. Oh well.Fireworks
T
0

Here is another option with gsub/strrep in base R

gsub("(.)", strrep("\\1", 2), a)
#[1] "aabbcc"

data

a <- 'abc'
Telegraphy answered 9/6, 2020 at 4:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.