创建“滞后”数据框架

时间:2013-09-03 17:22:56

标签: r dataframe

我有以下数据框,并希望将前两列中的所有列向下移动。基本上,我希望看到一个“滞后”的数据框架。似乎有很多关于如何为单个列获取此内容(请参阅here),但没有选择大多数列。

My data = 
d1 <- data.frame(month = c("jan", "feb", "mar", "apr", "may", "june"),
                conv =  c(1, 3, 6, 2, 3, 8),
                month = c("jan", "feb", "mar", "apr", "may", "june"),
                visit =  c( 1,  2,  4,  8, 16, 32),
                click =  c(64, 62, 36,  5,  6,  3))
d1

Desired output = 
d2 <- data.frame(month = c("jan", "feb", "mar", "apr", "may", "june"),
                conv =  c(1, 3, 6, 2, 3, 8),
                month = c(NA, "jan", "feb", "mar", "apr", "may"),
                visit =  c( NA, 1,  2,  4,  8, 16),
                click =  c(NA, 64, 62, 36,  5,  6))
d2

帮助?!

1 个答案:

答案 0 :(得分:1)

便宜的方法:

cbind(d1[,1:2],head(rbind(NA,d1),-1)[,-(1:2)])

结果:

  month conv month.1 visit click
1   jan    1    <NA>    NA    NA
2   feb    3     jan     1    64
3   mar    6     feb     2    62
4   apr    2     mar     4    36
5   may    3     apr     8     5
6  june    8     may    16     6