46

I want to repeat a vector N times but element-wise, not the whole vector.

For instance, I have:

v <- c('a', 'b')

Say I want to repeat n times:

n <- 3

I want:

vfill <- c(rep(v[1], n), rep(v[2], n))
print(vfill)
[1] "a" "a" "a" "b" "b" "b"

My best solution to date:

ffillv <- function(i) rep(v[i], n)
c(sapply(seq_len(length(v)), ffillv))

I am interested in fast & scalable solutions, for instance using rbind, plyr, etc.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Patrick
  • 1,561
  • 2
  • 11
  • 22
  • 14
    Why not `rep(v, each = 3)`? Can you clarify what you're trying to do? – A5C1D2H2I1M1N2O1R2T1 Feb 28 '13 at 17:22
  • @AnandaMahto Exactly what I was looking for. I have a somewhat complex objective function to optimize, built on "ragged" data. I use the plyr split-apply-combine philosophy. In the analysis process, I wanted to access some low-level intermediate data and combine it in a data.frame. I learned one way to combine as I wanted to using ldply, but that particular way necessitated the type of expansion I asked about. To your point, the way I am doing it may not be optimal! I may have further questions in the near future about it. Thanks. – Patrick Feb 28 '13 at 22:36

1 Answers1

101
rep(v, each=3)

or

rep(v, each=n)

where you have n defined

larrydag
  • 1,183
  • 1
  • 8
  • 4