Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用另一个data.table对data.table进行子集设置_R_Data.table_Subset - Fatal编程技术网

R 使用另一个data.table对data.table进行子集设置

R 使用另一个data.table对data.table进行子集设置,r,data.table,subset,R,Data.table,Subset,我有dt和dt1数据表 dt<-data.table(id=c(rep(2, 3), rep(4, 2)), year=c(2005:2007, 2005:2006), event=c(1,0,0,0,1)) dt1<-data.table(id=rep(2, 5), year=c(2005:2009), performance=(1000:1004)) dt id year event 1: 2 2005 1 2: 2 2006 0 3: 2 200

我有
dt
dt1
数据表

dt<-data.table(id=c(rep(2, 3), rep(4, 2)), year=c(2005:2007, 2005:2006), event=c(1,0,0,0,1))
dt1<-data.table(id=rep(2, 5), year=c(2005:2009), performance=(1000:1004))

dt

   id year event
1:  2 2005     1
2:  2 2006     0
3:  2 2007     0
4:  4 2005     0
5:  4 2006     1

dt1

   id year performance
1:  2 2005        1000
2:  2 2006        1001
3:  2 2007        1002
4:  2 2008        1003
5:  2 2009        1004
我尝试使用以下代码执行此操作:

dt.sub<-dt[dt[,c(1:2)] %in% dt1[,c(1:2)],]

dt.sub使用
merge

merge(dt,dt1, by=c("year","id"))
   year id event performance
1: 2005  2     1        1000
2: 2006  2     0        1001
3: 2007  2     0        1002
输出-

> dt[dt1,nomatch=0]
   id year event performance
1:  2 2005     1        1000
2:  2 2006     0        1001
3:  2 2007     0        1002

天哪,有时候解决方案很简单,你看不到。。。谢谢非常感谢!可能这一个在非常大的
数据中更快。table
s。如果您不想使用
performance
列,那么执行
dt[dt1,list(event),nomatch=0L]
应该要快一点…
数据。table
提供了自己的
merge
方法,它可以按照这些思路工作。我希望速度是相似的。
?merge
已经提到
X[Y…]
merge
快,但是它没有那么慢(特别是对于这个问题中的任务)。@Riccardo,不,只要你不使用
:=
,就不会发生引用更新。你可以自己试试。Do
ans
setkeyv(dt,c('id','year'))
setkeyv(dt1,c('id','year'))
dt[dt1,nomatch=0]
> dt[dt1,nomatch=0]
   id year event performance
1:  2 2005     1        1000
2:  2 2006     0        1001
3:  2 2007     0        1002