检查一个数据帧中是否存在值

use*_*306 32 r

我有两个具有相同列名(C)的数据框(A,B),但在该列中可以有不同的唯一值.我想检查数据框(A)中的列(C)中的'值'是否存在于数据帧(B)中.

A = data.frame(C=c(1,2,3,4))
B = data.frame(C=c(1,3,4,7))
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我想检查B中是否存在'2'是否有任何一个没有循环的衬里,因为我有相当大的文件,并且必须在每一行检查这个.

Ric*_*rta 72

使用%in%方法如下

A$C %in% B$C
Run Code Online (Sandbox Code Playgroud)

这将告诉你A列C的哪些值在B中.

返回的是逻辑向量.在您的示例的特定情况下,您将获得:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE
Run Code Online (Sandbox Code Playgroud)

您可以将其用作行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
Run Code Online (Sandbox Code Playgroud)

我们也可以否定它:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C
Run Code Online (Sandbox Code Playgroud)



如果您想知道特定值是否在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
Run Code Online (Sandbox Code Playgroud)