【问题标题】:Keep only elements of a list which contain a string in another vector (R)仅保留列表中包含另一个向量 (R) 中的字符串的元素
【发布时间】:2020-02-13 12:02:21
【问题描述】:

我有一个字符串关键字向量和一个包含许多字符串元素的列表。我想保留列表中至少包含一个来自向量的字符串的元素。

我已尝试使用 dplyr、%in% 等进行过滤。

这是一个例子:

words <- c("find", "these", "words")

paragraph <- list(text1 = c("these", "words", "are", "helpful"),
              text2 = c("nothing", "to", "see", "here"),
              text3 = c("we", "can", "find", "one", "here"))

我希望得到一个仅包含 text1 和 text3 的列表。

谢谢!

【问题讨论】:

    标签: r regex string list find


    【解决方案1】:

    一个选项是Filter 来自base R。用%in% 创建一个逻辑vectorany 包装

    Filter(function(x) any(words %in% x), paragraph)
    #$text1
    #[1] "these"   "words"   "are"     "helpful"
    
    #$text3
    #[1] "we"   "can"  "find" "one"  "here"
    

    或使用sapply

    paragraph[sapply(paragraph, function(x) any(words %in% x))]
    

    或者使用lengthsintersect

    paragraph[lengths(Map(intersect, list(words), paragraph)) > 0]
    

    keep 来自purrr

    library(purrr)
    keep(paragraph, ~ any(words %in% .x))
    

    【讨论】:

    • 哇哦!非常感谢,最后一个选项就像一个魅力。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    相关资源
    最近更新 更多