重复数据帧N次 [英] Repeat data.frame N times

查看:119
本文介绍了重复数据帧N次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框架

  data.frame(a = c(1,2,3),b = c(1,2,3))
ab
1 1 1
2 2 2
3 3 3

,我想把它变成

  ab 
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

或重复N次。在R中有这么容易的功能吗?谢谢!

解决方案

你可以使用 replicate() code> rbind 结果一起回来。轮流名称自动更改为从1:nrows运行。

  d<  -  data.frame(a = c(1,2,3),b = c ,3))
n < - 3
do.call(rbind,replicate(n,d,simplified = FALSE))
  d [rep(seq_len(nrow(d)),n),] 


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

and I want to turn it into

  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

or repeat it N times. Is there an easy function to do this in R? Thanks!

解决方案

You can just use replicate(), then rbind the result back together. The rownames are automatically altered to run from 1:nrows.

d <- data.frame(a = c(1,2,3),b = c(1,2,3))
n <- 3
do.call("rbind", replicate(n, d, simplify = FALSE))

A more traditional way is to just use indexing, but here the rowname altering is not quite so neat (but more informative):

 d[rep(seq_len(nrow(d)), n), ]

这篇关于重复数据帧N次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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