Detect in list2 if there are any strings (whole or part of bigger string) that is contained in list1

时光怂恿深爱的人放手 提交于 2019-12-11 21:15:27

问题


I have two lists:

list1<-list("q","w","e","r","t")
list2<-list("a","a","aq","c","f","g")

I need a code that will give TRUE because q is in the third cell of list2. I need to search for every cell of list1 in list2. I mean that I need to search every cell of list2 for any strings that are contained in every cell of list1. Matching should be as for the whole match but also for partial (if string from list1 is a part of the bigger string in list2) and in both cases I need to receive TRUE.


回答1:


any(sapply(list1, grepl, list2))
# [1] TRUE

Or equivalently

greplv <- Vectorize(grepl, 'pattern')
any(greplv(list1, list2))
# [1] TRUE



回答2:


Not sure if the list input is particularly important here in that case. Here is a way that avoids using any iteration functions like apply. We can collapse the input list into a single regular expression pattern and then check the whole of the second list with it. You may need to be careful if you have any special characters in list1, though that is the case for any string matching method.

library(stringr)
list1 <- list("q", "w", "e", "r", "t")
list2 <- list("a", "a", "aq", "c", "f", "g")

pat <- unlist(list1) %>% str_c(collapse = "|")

list2 %>%
  unlist %>%
  str_detect(pat) %>%
  any
#> [1] TRUE

Created on 2019-05-16 by the reprex package (v0.2.1)



来源:https://stackoverflow.com/questions/56174477/detect-in-list2-if-there-are-any-strings-whole-or-part-of-bigger-string-that-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!