1

I'm trying to find a way to check whether a list contains an element that itself contains a particular string. Finding an exact match is simple with %in%:

list1 <- list("a","b","c")
"a" %in% list1
[1] TRUE

But it only works if the element is identical, i.e. it doesn't return TRUE if the element only contains the string:

list2 <- list("a,b","c,d")
"a" %in% list2
[2] FALSE

Is there a way to generate TRUE for the second example? Thanks in advance.

heds1
  • 2,799
  • 2
  • 13
  • 29
  • 6
    Something like `any(grepl("a", unlist(list2)))` ? Or if they are always comma separated then `"a" %in% unlist(strsplit(as.character(list2), ","))` – Ronak Shah Dec 01 '17 at 01:23
  • commenting on @ronak-shah 's answer, if every element in `list2` is just a simple character string, `unlist()` can be omitted. `any(grepl("a",list2))` should do. – Yue Y Dec 01 '17 at 01:36
  • I don't know anything about r. But I did find this thread: https://stackoverflow.com/questions/30180281/how-can-i-check-if-multiple-strings-exist-in-another-string – John Mitchell Dec 01 '17 at 01:47
  • If you can use `c` instead of `list`, this question is simpler. – alistaire Dec 01 '17 at 01:57

2 Answers2

2

Could you try flipping it around and using

any(list2 %like% 'a')

The any() is included because without it the output is : [1] TRUE FALSE

Joseph Wood
  • 6,489
  • 2
  • 28
  • 62
brett
  • 131
  • 6
1
library(stringi)

list2 <- list("a,b","c,d")

stri_detect_fixed(list2, "a")
## [1]  TRUE FALSE

stri_detect_fixed(list2, "b")
## [1]  TRUE FALSE

stri_detect_fixed(list2, "c")
## [1] FALSE  TRUE

stri_detect_fixed(list2, "d")
## [1] FALSE  TRUE

stri_detect_fixed(list2, "q")
## [1] FALSE FALSE
hrbrmstr
  • 74,560
  • 11
  • 127
  • 189