简体   繁体   English

R-在某些条件下比较矩阵中的行

[英]R- Comparing rows in matrix for certain conditions

I have a history table (table: HT) containing purchase information in the following structure 我有一个历史表(表:HT),其中包含以下结构的购买信息

Supplierno itemno price 供应商 无项目无 价格
ABC123 101 50 ABC123 101 50
ABC124 105 55 ABC124 105 55
BCD201 103 60 BCD201 103 60
BCD211 103 60 BCD211 103 60
EFG103 103 45 EFG103 103 45

Then I get new data in the same format(table: NT) on a periodic basis. 然后,我会定期获取相同格式(表:NT)的新数据。 I want to determine cases in the new data feed, where vendors are supplying the same item at prices . 我想确定新数据提要中的案例,其中卖方以价格提供相同的项目。 I wanted to the equivalent of a SQL query that will do a 我想相当于一个SQL查询,它将执行

select NT.* from newtable where NNT.itemno=HT.itemno AND NT.price<>1.2*HT.price 从newtable中选择NT。*,其中NNT.itemno = HT.itemno AND NT.price <> 1.2 * HT.price

I tried HT[HT[(HT.itemno==NT.itemno) & (HT.price!=NT.price)] but always get 0 results even though there are instances that should get picked up. 我试过HT [HT [(HT.itemno == NT.itemno)&(HT.price!= NT.price)],但即使有实例需要拾取,也总是得到0结果。

Somehow comparing columns in a row works well with this approach, but not same column across rows 以某种方式比较行中的列可以使用此方法很好地工作,但行之间的列不相同

I know I can run loops but my HT table is large(>1M) and understand thinking vectors will be more efficient. 我知道我可以运行循环,但是我的HT表很大(> 1M),并且了解思维向量会更有效。

Look forward for inputs and guidance 期待输入和指导

Using data.table you can also try: (reusing @Wave's example) 使用data.table您还可以尝试:(重用@Wave的示例)

library(data.table)
HT=data.table(supplier=c("ABC123","ABC124","BCD201"),itemno=101:103,price=c(50,55,60))
NT=data.table(supplier=c("ABC123","ABC124","BCD201"),itemno=101:103,price=c(50,55,65))
merge(HT,NT,by=c("itemno","supplier"))[price.x!=price.y]

To recreate you data: 要重新创建数据:

HT=data.frame(supplier=c("ABC123","ABC124","BCD201"),itemno=101:103,price=c(50,55,60))

NT=data.frame(supplier=c("ABC123","ABC124","BCD201"),itemno=101:103,price=c(50,55,65))

To select from the new dataframe the cases where the price is changed: 要从新数据框中选择价格更改的情况:

NT[NT$itemno %in% HT$itemno & NT$price!=HT$price,]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM