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

问题描述 投票:0回答:2

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

A = data.frame(C = c(1,2,3,4))
B = data.frame(C = c(1,3,4,7))
r dataframe membership
2个回答
117
投票

使用

%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



如果你想知道某个特定值是否在 B$C 中,请使用相同的函数:

  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

0
投票

您还可以使用

is.element
。它检查
A$C
中的元素是否也在
B$C
中,就像
%in%
一样。

is.element(A$C, B$C)
# [1]  TRUE FALSE  TRUE  TRUE

如果您想要

A$C
B$C
中的值,也可以使用
intersect
。对于
A$C
中但不在
B$C
中的值,可以使用
setdiff

intersect(A$C, B$C)
# [1] 1 3 4

setdiff(A$C, B$C)
# [1] 2
© www.soinside.com 2019 - 2024. All rights reserved.