问题
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