R finding rows of a data frame where certain columns match those of another [duplicate]

我是研究僧i 提交于 2019-11-30 02:24:17

If you use data.tables and key by the columns you want to match, then you can accomplish your goal in one line:

    tData[tBounce, Bounced := 1L]



Here is the full process:

library(data.table)
keys <- c("Email", "Campaign")
tData <- data.table(testData, key=keys)
tBounce <- data.table(testBounce, key=keys)

tData[tBounce, Bounced := 1L]

Results:

tData

                Email   Manual Campaign Bounced Opened Clicked ClickThru Unsubscribed
1:    block@quote.com EIFLS0LS        1       1      0       0         0            0
2:     data@frame.com EIFLS0LS        1       0      0       0         0            0
3:          ht@ml.com EIFLS0LS        1       1      0       0         0            0
4: stack@exchange.com EIFLS0LS        1       0      0       0         0            0
5: stack@overflow.com EIFLS0LS        1       1      0       0         0            0
6:     tele@phone.com EIFLS0LS        1       0      0       0         0            0
> 

You want the function merge.

merge is commonly used to merge two tables by one similar common, but the by argument can allow multiple columns:

merge(testData, testBounced, by=c("Email", "Campaign"))

All pairs of Email and Campaign that don't match will be discarded by default. That's controllable by the arguments all.x and all.y, which default to FALSE.

The default argument for by is intersect(names(x, y)), so you technically don't need to specify the columns in this case, but it's good for clarity.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!