6

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
  • 3,203
  • 2
  • 17
  • 32
  • 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
  • 1
    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

3 Answers3

4

Could you try flipping it around and using

library(data.table)
any(list2 %like% 'a')

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

M--
  • 25,431
  • 8
  • 61
  • 93
brett
  • 151
  • 6
2
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
  • 77,368
  • 11
  • 139
  • 205
2

Without using an additional library.

# You can get the index of the match with grep
grep('a', list2)

# You can get the TRUE/FALSE you wanted by checking the length
length(grep('a', list2)) > 0
Cyrille
  • 3,427
  • 1
  • 30
  • 32