![](/img/trans.png)
[英]R data.table replacing an index of values from another data.table
[英]R: find all observations from data.table with values from another data.table
我有R中的兩個數據表: DT1
具有約30K obervations 5個變量: userID
, userName
, productID
, productName
, usersRate
, DT2
僅具有500 2個變量的意見: productID
, similarProductID
。 我想從DT1
查找所有productID
與DT2中的同類產品similarProductID
相同的行。 我已經嘗試了DT1[which(DT1$productID==DT2$similarProductID)]
和DT1[which(DT1$productID==intersect(DT1$productID,DT2$similarProductID))]
但沒有成功,我收到了觀察結果太少。 有什么主意我該怎么做?
最快的方法是聯接:
#mock data
DT1<-data.table(userID=1:30000,userName=sample(LETTERS,30000,T),productID=30001:60000,productName=sample(LETTERS,30000,T),userRate=runif(30000))
DT2<-data.table(productID=1:500,similarProductId=sample(30001:60000,500))
#set keys
setkey(DT1,productID)
setkey(DT2,similarProductId)
#join
DT1[DT2]
productID userID userName productName userRate productID.1
1: 30014 14 L R 0.87649196 473
2: 30025 25 E A 0.02237395 326
3: 30027 27 H Z 0.43986360 198
4: 30065 65 V K 0.33047666 240
5: 30123 123 R X 0.38637559 210
---
496: 59575 29575 U A 0.41036652 214
497: 59665 29665 C E 0.67345907 45
498: 59724 29724 F Y 0.18853101 81
499: 59764 29764 D X 0.50271854 386
500: 59790 29790 Z A 0.02222698 397
我懷疑這種方式是否比Troy的加入答案更快,但是您可以在R中使用merge函數。
DT1<-data.frame(userID=1:30000,userName=sample(LETTERS,30000,T),productID=30001:60000,productName=sample(LETTERS,30000,T),userRate=runif(30000))
DT2<-data.frame(productID=sample(30001:60000,500), similarproductID=sample(30001:60000,500))
colnames(DT2)<-c("BadproductID","productID") #Do this to match the colname in DT1
DTMerged<-merge(DT1,DT2, by="productID") #Should give you all your matches without NA's
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.