【问题标题】:Check which words show up at least once within words from another vector检查哪些词在另一个向量的词中至少出现一次
【发布时间】:2016-03-07 06:14:48
【问题描述】:

假设我们有一个单词列表:

words = c("happy","like","chill")

现在我有了另一个字符串变量:

s = "happyMeal"

我想检查 words 中的哪个单词与 s 中的匹配部分。 所以 s 可以是“happyTime”、“happyFace”、“happyHour”,但只要里面有“happy”,我希望我的结果返回字符串向量单词中单词“happy”的索引。

这个问题与帖子中提出的问题相似但不完全相同:Find a string in another string in R

【问题讨论】:

    标签: r string matching word


    【解决方案1】:

    您可以使用sapply 遍历您要搜索的每个单词,使用grepl 来确定该单词是否出现在s 中:

    sapply(words, grepl, s)
    # happy  like chill 
    #  TRUE FALSE FALSE 
    

    如果 s 是单个词,则 sapplygrepl 返回一个逻辑向量,您可以使用它来确定匹配的词:

    words[sapply(words, grepl, s)]
    # [1] "happy"
    

    s 包含多个单词时,sapplygrepl 返回一个逻辑矩阵,您可以使用列和来确定哪些单词至少出现一次:

    s <- c("happyTime", "chilling", "happyFace")
    words[colSums(sapply(words, grepl, s)) > 0]
    # [1] "happy" "chill"
    

    【讨论】:

      【解决方案2】:

      这是一个使用来自stringistri_detect 的选项

      library(stringi)
      words[stri_detect_regex(s, words)]
      #[1] "happy"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-15
        • 2023-03-23
        • 1970-01-01
        • 2019-11-02
        • 2019-03-15
        • 2022-12-03
        相关资源
        最近更新 更多