检查一个数据框列中的值是否存在于第二个数据框中

2024-04-09

我有两个数据框(A 和 B),都有一个列“C”。我想检查数据框 A 中“C”列中的值是否存在于数据框 B 中。

A = data.frame(C = c(1,2,3,4))
B = data.frame(C = c(1,3,4,7))

Use %in%如下

A$C %in% B$C

这将告诉您 A 的 C 列的哪些值在 B 中。

返回的是一个逻辑向量。在您的示例的具体情况下,您将得到:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

您可以将其用作行的索引A或作为索引A$C获取实际值:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

我们也可以否定它:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C


If you want to know if a specific value is in B$C, use the same function:
  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

检查一个数据框列中的值是否存在于第二个数据框中 的相关文章

随机推荐