R data.table替换了另一个data.table中值的索引 [英] R data.table replacing an index of values from another data.table
问题描述
您好,他仍在尝试找出data.table。如果我有一个data.table值(例如下面的值),用其他data.table中的值替换值的最有效方法是什么?
Hi still trying to figure out data.table. If I have a data.table of values such as those below, what is the most efficient way to replace the values with those 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'))
我要尝试的操作要做的是用 date_id
和 id
匹配的a中的px和vol替换我有点困惑这样做-我想可能会有类似的方法,但是我认为这在实践中不可行。
What I'm trying to do is replace the px and vol in b with those in a where date_id
and id
match I'm a little flummoxed with this - I would suppose that something along the lines of might be the way to go but I don't think this 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)]
编辑
我尝试了以下
t = a[b,roll=T]
t[!is.na(px),list(px.1:=px,vol.1=vol),by=list(date_id,id)]
并收到错误消息
Error in `:=`(px.1, px) :
:= is defined for use in j only, and (currently) only once; i.e., 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.
推荐答案
如果要替换<$中的值c $ c> b ,您可以使用前缀 i。
。来自关于1.7版的新闻。 10
If you are wanting to replace the values within b
you can use the prefix i.
. From the NEWS regarding version 1.7.10
前缀i。现在可以在j中使用它来引用i的继承
列,否则它们将被x中具有相同名称
的列屏蔽。
The prefix i. can now be used in j to refer to join inherited columns of i that are otherwise masked by columns in x with the same name.
b[a, `:=`(px = i.px, vol = i.vol)]
这篇关于R data.table替换了另一个data.table中值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!