如何返回包含R中另一个向量中至少一个字符串的向量的索引

时间:2017-11-12 22:38:49

标签: r string

我有一个包含动词的列表。我有另一个包含句子的列表。如何返回在该句子的动词列表中至少包含动词的句子列表的索引?

verbList <- c("punching", "kicking", "jumping", "hopping")
sentenceList <- c("I am punching", "I like pineapples", "I am hopping", "I am kicking and jumping")

我希望它返回索引1,3和4

2 个答案:

答案 0 :(得分:2)

来自stringrrebus的解决方案。我们可以先拆分字符串,然后使用str_which检查模式是否在向量中以返回索引。

library(stringr)
library(rebus)

# Check the index
result <- str_which(sentenceList, or1(verbList))
result
# [1] 1 3 4

答案 1 :(得分:2)

不使用其他套餐,我们可以排序&#34;或&#34;使用|将不同的搜索字词组合在一起,如下所示:

原始问题:

verbList <- list("punching, kicking, jumping, hopping")
sentenceList <- c("I am punching", "I like pineapples", "I am hopping", "I am kicking and jumping")

    v <- gsub(", ", "|", verbList) 
    grep(v, sentenceList)

新问题:

verbList <- c("punching", "kicking", "jumping", "hopping")
sentenceList <- c("I am punching", "I like pineapples", "I am hopping", "I am kicking and jumping")
v <- paste(verbList, collapse = "|")
grep(v, sentenceList)