首页 > 解决方案 > 如何将 %in% 的使用与 OR 运算符结合使用?

问题描述

我想查找并测试一个集合(“集合 A”)中的值是否出现在集合B​​集合 C 中。我试图为此目的使用运算符,但不知道如何将它与或者。%in%

底部有一个可重现的示例,但我想要得到的要点如下:

set_a %in% (set_b | set_c) 

我想知道 set_a 中的哪些值存在set_bset_c或两者中。

例子

#Step 1 :: Creating the data

    set_a <- unlist(strsplit("Eden Kendall Cali Ari Madden Leo Stacy Emmett Marco Bridger Alissa Elijah Bryant Pierre Sydney Luis", split=" "))

    set_b <- as.data.table(unlist(strsplit("Kathy Ryan Brice Rowan Nina Abram Miles Kristina Gabriel Madden Jasper Emmett Marco Bridger Alissa Elijah Bryant Pierre Sydney Luis", split=" ")))
    set_c <- as.data.table(unlist(strsplit("Leo Stacy Emmett Marco Moriah Nola Jorden Dalia Kenna Laney Dillon Trystan Elijah Bryant Pierr", split=" ")))


    NamesList <- list(set_b, set_c) #set_b and set_c will now become neighboring data.table dataframes in one list.
    > NamesList
    [[1]]
              V1
     1:    Kathy
     2:     Ryan
     3:    Brice
     4:    Rowan
     5:     Nina
     6:    Abram
     7:    Miles
     8: Kristina
     9:  Gabriel
    10:   Madden
    11:   Jasper
    12:   Emmett
    13:    Marco
    14:  Bridger
    15:   Alissa
    16:   Elijah
    17:   Bryant
    18:   Pierre
    19:   Sydney
    20:     Luis

    [[2]]
             V1
     1:     Leo
     2:   Stacy
     3:  Emmett
     4:   Marco
     5:  Moriah
     6:    Nola
     7:  Jorden
     8:   Dalia
     9:   Kenna
    10:   Laney
    11:  Dillon
    12: Trystan
    13:  Elijah
    14:  Bryant
    15:   Pierr

#Step 2 :: Checking which values from set_a appear in either set_b or set_c

    matches <- set_a %in% (set_b | set_c)
    #doesn't work!

有任何想法吗?顺便说一句,使用 data.table 格式对我来说很重要。

标签: roperators

解决方案


您可以单独尝试条件

set_a %in% set_b | set_a %in% set_c

或使用unionunique

set_a %in% union(set_b, set_c)

set_a %in% unique(c(set_b, set_c))

推荐阅读