我有两个数据框(A 和 B),都有一列“C”。我想检查数据框 A 中“C”列中的值是否存在于数据框 B 中。
A = data.frame(C = c(1,2,3,4))
B = data.frame(C = c(1,3,4,7))
最佳答案
使用 %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
关于r - 检查一个数据框列中的值是否存在于第二个数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13774773/