I have the following data frame:
data.frame(a = c(1,2,3),b = c(1,2,3))
a b
1 1 1
2 2 2
3 3 3
I want to repeat the rows n times. For example, here the rows are repeated 3 times:
a b
1 1 1
2 2 2
3 3 3
4 1 1
5 2 2
6 3 3
7 1 1
8 2 2
9 3 3
Is there an easy function to do this in R? Thanks!
EDIT: updated to a better modern R answer.
You can use
replicate(), thenrbindthe result back together. The rownames are automatically altered to run from 1:nrows.A more traditional way is to use indexing, but here the rowname altering is not quite so neat (but more informative):
Here are improvements on the above, the first two using
purrrfunctional programming, idiomatic purrr:and less idiomatic purrr (identical result, though more awkward):
and finally via indexing rather than list apply using
dplyr: