1

我有以下数据框,并且想将除前两列之外的所有列向下移动。基本上,我想看到一个“滞后”的数据框。似乎有很多关于如何为单个列获取此信息(请参见此处),但没有选择大多数列。

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

帮助?!

4

1 回答 1

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
于 2013-09-03T17:31:32.130 回答