2017-09-14 46 views
1

我有这个表R:复制表中一列

Name  ID Year Month Date 
John  8  2017 7  16  
Carol 90 2017 7  30 
Bug  9  2017 7  1 

我想复制这个同桌的4倍,所有的值应该是相同的。除了每月需要​​增加1的月份列之外。决赛桌应该看起来像这样:

Name  ID Year Month Date 
John  8  2017 7  16 
Carol 90 2017 7  30 
Bug  9  2017 7  1 
John  8  2017 8  16 
Carol 90 2017 8  30 
Bug  9  2017 8  1 
John  8  2017 9  16 
Carol 90 2017 9  30 
Bug  9  2017 9  1 
John  8  2017 10  16 
Carol 90 2017 10 30 
Bug  9  2017 10 1 
John  8  2017 11 16 
Carol 90 2017 11 30 
Bug  9  2017 11 1 

请在R中如何高效地做到这一点。非常感谢!

+0

“请指出如何在R中有效地做到这一点”.....在R一切都很有效率:-)) – PoGibas

回答

2

如果这是你的数据框:

df = read.table(text = "Name ID Year Month Date 
      John 8 2017 7 16 
      Carol 90 2017 7 30 
      Bug 9 2017 7 1", header = TRUE) 

那么这就是你的数据框重复:

df2 = df[rep(rownames(df), 4),] 

而这又是它,但与几个月递增:

df2$Month = df2$Month + rep(0:3, 3) 

在更一般的情况下:

m = 4 # <-- number of rows desired 
df2 = df[rep(rownames(df), m), ] 
df2$Month = df2$Month + rep(0:m, nrow(df)) 
+2

对于你的最后一行,你想'df2 $ Month + rep(0:3,each = nrow(DF))'。 – lmo

+0

错误'[.data.table'(df,rep(rownames(df),m),): 当我是一个data.table(或字符向量)时,要加入的列必须使用' on ='参数(请参阅?data.table)或键入x(即排序,并标记为排序,请参阅?setkey)。由于x在RAM中排序,键控连接可能对超大型数据具有进一步的优势。 – Pree

+0

这有效:df2 < - df [rep(1:nrow(df),m),]。这是我的错,谢谢你指出lebelinoz! – Pree