我有一个像这样的数据框:
DF = data.frame(ID=rep(c("a","b","c"),each=3), Class=c("X","Y","Z"), Period=c("12/12","13/04","13/08"))
DF
ID Class Period
1 a X 12/12
2 a Y 13/04
3 a Z 13/08
4 b X 12/12
5 b Y 13/04
6 b Z 13/08
7 c X 12/12
8 c Y 13/04
9 c Z 13/08
我希望ID和Period的每个组合都有一个colunm,其中包含每个ID的前一个句点的Class值。像这样:
ID Class Period PrevClass PrevPeriod
1 a X 12/12 <NA> <NA>
2 a Y 13/04 X 12/12
3 a Z 13/08 Y 13/04
4 b X 12/12 <NA> <NA>
5 b Y 13/04 X 12/12
...
只是在我的数据框中添加,并非所有ID都会有每个期间的记录。我通过ODBC从数据库中获取数据,只是想一想用SQL做它比用R做它更容易。
提前致谢!
答案 0 :(得分:2)
library(data.table)
DF = data.table(
ID=(rep(c("a","b","c"),each=3)),
Class=(c("X","Y","Z")),
Period=(c("12/12","13/04","13/08"))
)
#setting the order correctly, just in case
setkeyv(DF, c('ID', 'Class'))
#creating a column prevperiod with NA and the first n-1 elements of period within each ID
DF[,prevperiod := c(NA, head(Period,-1)), by = ID]