【问题标题】:How to combine the use of %in% with OR operator?如何将 %in% 的使用与 OR 运算符结合使用?
【发布时间】:2019-11-12 21:02:49
【问题描述】:

我想查找并测试一组(“set A”)中的值是否出现在 either set B set C。我试图使用%in% 运算符用于此目的,但无法弄清楚如何将其与 OR 结合。

下面是一个可重复的示例,但我想要得到的只是这样的要点:

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 格式对我来说很重要。

【问题讨论】:

  • 单独试用set_a %in% set_b | set_a %in% set_c 或使用union , set_a %in% union(set_b, set_c)
  • 你可以简单地 rbind 两个列表,即set_a %in% rbindlist(NamesList)$V1
  • @RonakShah 的答案正是我想要的。谢谢。

标签: r operators


【解决方案1】:

你可以单独试试条件

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))

【讨论】:

  • 我最终使用了union() 解决方案。但是,在我的数据中(上面的示例也提供了),set_b 和 set_c 都有一个名为 V1 的标头。因此,代码为:set_a %in% union(set_b$V1, set_c$V1).
【解决方案2】:

我们可以使用

Reduce(`|`, lapply(list(set_b, set_c), `%in%`, set_a))

【讨论】:

  • 我明白了:Warning message: In f(init, x[[i]]) : longer object length is not a multiple of shorter object length
猜你喜欢
  • 2022-11-23
  • 2014-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-29
  • 1970-01-01
  • 2013-09-10
相关资源
最近更新 更多