Hi, still trying to figure out a data table. If I have a data table with values like the ones below, then what is the most efficient way to replace the values with values from another data table.
set.seed(123456) a=data.table( date_id = rep(seq(as.Date('2013-01-01'),as.Date('2013-04-10'),'days'),5), px =rnorm(500,mean=50,sd=5), vol=rnorm(500,mean=500000,sd=150000), id=rep(letters[1:5],each=100) ) b=data.table( date_id=rep(seq(as.Date('2013-01-01'),length.out=600,by='days'),5), id=rep(letters[1:5],each=600), px=NA_real_, vol=NA_real_ ) setkeyv(a,c('date_id','id')) setkeyv(b,c('date_id','id'))
What I'm trying to do is replace px and vol in b with the ones where date_id and id same, I'm a little confused by this - I would suggest that something like strings be the way to go, but I don’t think it will work in practice.
b[which(b$date_id %in% a$date_id & b$id %in% a$id),list(px:=a$px,vol:=a$vol)]
EDIT
I tried the following
t = a[b,roll=T] t[!is.na(px),list(px.1:=px,vol.1=vol),by=list(date_id,id)]
and got an error message
Error in `:=`(px.1, px) : := is defined for use in j only, and (currently) only once; ie, DT[i,col:=1L] and DT[,newcol:=sum(colB),by=colA] are ok, but not DT[i,col]:=1L, not DT[i]$col:=1L and not DT[,{newcol1:=1L;newcol2:=2L}]. Please see help(":="). Check is.data.table(DT) is TRUE.