R data.table, replacing the index of values ​​from another data.table

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. 
+4
source share
2 answers

If you want to replace the values ​​in b , you can use the i. prefix i. . From NEWS regarding version 1.7.10

Prefix i. now you can use columns i in j to refer to the attached inheritance, which are otherwise masked by columns in x with the same name.

 b[a, `:=`(px = i.px, vol = i.vol)] 
+8
source

It doesn't seem like you need to roll from your description, and it seems that you want to do this when you get your error:

 t[!is.na(px),`:=`(px.1=px,vol.1=vol),by=list(date_id,id)] 
+2
source

Source: https://habr.com/ru/post/1482708/


All Articles