如何重复一个data.frame? [英] How can I repeat a data.frame?

查看:59
本文介绍了如何重复一个data.frame?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重复一次data.frame很容易,

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

mt2 <- rbind(mtcars, mtcars)

但是一般情况下,类似R的方式是什么?如果我想同时获得10份 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)

这很简洁,但似乎不符合R的精神。是否有更好的方法来执行此操作,或者使用向量回收的巧妙技巧?

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?

推荐答案

这是一个非常简单的方法:

Here's a very simple method:

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

或使用更好的语法:

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

正如下面的GSee所述,这里的区别是 rbind 将精确地复制行名,而使用索引将通过附加唯一行名数字。我想,唯一的解决办法是在事实之后设置行名(再次使用 rep )。

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.

这篇关于如何重复一个data.frame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆