How can I repeat a data.frame?

后端 未结 4 1489
Happy的楠姐
Happy的楠姐 2021-01-14 02:10

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

4条回答
  •  天命终不由人
    2021-01-14 02:51

    If you can tolerate another package:

    require(mefa)
    rep(mtcars,10)
    
    • works after all!

    It appears a little faster:

    system.time(mtcars[rep(1:nrow(mtcars),1e5),])
    system.time(mtcars[rep(seq_len(nrow(mtcars)),1e5),])
    system.time(rep(mtcars,1e5))
    

    Gives:

     user  system elapsed 
     17.41    0.19   17.89
     17.11    0.31   17.91
     6.79    0.70    7.67
    

    Caveats: 1) rep will not reproduce the row names; this is a separate step. 2) mefa::rep(mtcars,10) doesn't work as: Error: 'rep' is not an exported object from 'namespace:mefa'. Also mefa:::rep(mtcars,10) gives object 'rep' not found. Not sure why this is...

提交回复
热议问题