简体   繁体   English

R:提取一列中的唯一值与另一列中的值匹配

[英]R: Extract unique values in one column match by values in another column

I would like to print string from df1 if it does not exist in df2如果 df2 中不存在,我想从 df1 打印字符串

df1 <- data.frame(One = c("userID1", "userID5", "userID9"))
df2 <- data.frame(Two = c("userID2", "userID4", "userID1", "userID7"))

I would like to print string from df1 if it does not exist in df2如果 df2 中不存在,我想从 df1 打印字符串

Output <- data.frame(Two = c("userID5", "userID9"))

Thank you in advance.先感谢您。

You could use dplyr 's anti_join :您可以使用dplyranti_join

library(dplyr)

df1 <- data.frame(One = c("userID1", "userID5", "userID9"))
df2 <- data.frame(Two = c("userID2", "userID4", "userID1", "userID7"))

df1 %>% 
  anti_join(df2, by = c("One" = "Two"))

returns回报

      One
1 userID5
2 userID9

Or simply或者干脆

df1 <- data.frame(One = c("userID1", "userID5", "userID9"))
df2 <- data.frame(Two = c("userID2", "userID4", "userID1", "userID7"))

library(dplyr, warn.conflicts = F)
df1 %>%
  filter(!One %in% df2$Two)
#>       One
#> 1 userID5
#> 2 userID9

Created on 2021-08-19 by the reprex package (v2.0.1)reprex package (v2.0.1) 创建于 2021-08-19

Using data.table使用data.table

library(data.table)
setDT(df1)[!df2, on = .(One = Two)]
       One
1: userID5
2: userID9

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

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