Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I repeat a data.frame?

Tags:

dataframe

r

It's easy to repeat a data.frame once,

mt2 <- rbind(mtcars, mtcars)

But what's an R-like way to do this generally? If I want 10 copies of mtcars together I could

mt10 <- mtcars
for (i in 2:10) mt10 <- rbind(mt10, mtcars)

which is plenty concise, but seems not in the spirit of R. Is there a better way to do this, or a clever trick using vector recycling?

like image 751
Gregor Thomas Avatar asked Dec 04 '22 01:12

Gregor Thomas


2 Answers

Here's a very simple method:

mtcars[rep(1:nrow(mtcars),2),]

or using better "grammar":

mtcars[rep(seq_len(nrow(mtcars)),2),]

As GSee notes below, one difference here is that rbind will replicate the row names exactly, while using indexing will force unique row names by appending digits. Off the top of my head, I think the only fix would be to set the row names (again using rep) after the fact.

like image 85
joran Avatar answered Dec 05 '22 14:12

joran


@joran's answer is very elegant and you should use it if duplicating the rownames isn't required. However, this way will also duplicate the rownames:

do.call(rbind, replicate(10, mtcars[1:10, ], simplify=FALSE))

like image 36
Matthew Plourde Avatar answered Dec 05 '22 15:12

Matthew Plourde