我有一个如下所示的数据集:
set.seed(1234)
DT<-data.table(id=c(rep(c("a","b","c","d"),5)),
year=rep(seq(from = 2010.5,to=2012.5,by = .5),each=4),
value=rnorm(20,10,1))
DT
id year value
1: a 2010.5 8.792934
2: b 2010.5 10.277429
3: c 2010.5 11.084441
4: d 2010.5 7.654302
5: a 2011.0 10.429125
6: b 2011.0 10.506056
7: c 2011.0 9.425260
8: d 2011.0 9.453368
9: a 2011.5 9.435548
10: b 2011.5 9.109962
11: c 2011.5 9.522807
12: d 2011.5 9.001614
13: a 2012.0 9.223746
14: b 2012.0 10.064459
15: c 2012.0 10.959494
16: d 2012.0 9.889715
17: a 2012.5 9.488990
18: b 2012.5 9.088805
19: c 2012.5 9.162828
20: d 2012.5 12.415835
我想为每个ID添加3个相似的列,value_previous_6m
,value_previous_y
和value_next_y
。第10行应如下所示:
id year value value_previous_6m value_previous_y value_next_y
b 2011.5 9.109962 10.50606 10.27743 9.088805
我想避免使用plyr函数,因为总数据集非常大。
非常感谢, 添
编辑:我知道可以使用合并功能完成:
set.seed(1234)
DT<-data.table(id=c(rep(c("a","b","c","d"),5)),
year=rep(seq(from = 2010.5,to=2012.5,by = .5),each=4),
value=rnorm(20,10,1))
DT6mp <- copy(DT)
DT12mp <- copy(DT)
DT6mp[,year:=year-.5]
setkey(DT6mp,id,year);setkey(DT,id,year);setnames(DT6mp,"value","value6mp")
DT <- merge(DT,DT6mp,all.x=T,all.y=F,allow.cartesian=T)
DT12mp[,year:=year-1]
setkey(DT12mp,id,year);setkey(DT,id,year);setnames(DT12mp,"value","value12mp")
DT <- merge(DT,DT12mp,all.x=T,all.y=F,allow.cartesian=T)
DT
但我认为应该有更好的方法。
答案 0 :(得分:1)
You can use this approach ( I voluntary did not aggregated the 3 columns addition to make it clearer):
<style> .block1 {
color: #0000ff;
/*display: block;*/
font-family: 宋体:SimSun font-size: 1.41667em;
font-weight: bold;
line-height: 1.2;
margin-bottom: 0.67em;
margin-left: 0;
margin-right: 0;
margin-top: 24pt;
/* page-break-inside: avoid;*/
}
.calibre {
color: #4F81BD;
display: block;
font-family: "細明體", sans-serif;
font-size: 1em;
margin-bottom: 0;
margin-left: 5pt;
margin-right: 5pt;
margin-top: 0;
padding-left: 0;
padding-right: 0
}
.block2 {
color: red;
display: block;
font-family: "細明體", sans-serif;
margin-bottom: 3pt;
margin-left: 0;
margin-right: 0;
margin-top: 3pt;
padding-bottom: 0;
padding-left: 0;
padding-right: 0;
padding-top: 0;
text-align: justify
}
</style>