Reputation: 1468
I have the following data frame and want to shift all but the first two columns down. Basically, I want to see a 'lagged' data frame. There seems to be a lot on how to get this for a single column (see here), but nothing to select most of the columns.
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
Help?!
Upvotes: 1
Views: 78
Reputation: 12819
A cheap method:
cbind(d1[,1:2],head(rbind(NA,d1),-1)[,-(1:2)])
Result:
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
Upvotes: 1