1

I am looking to partial match string using %in% operator in R when I run below I get FALSE

'I just want to partial match string' %in% 'partial'
 FALSE

Expected Output is TRUE in above case (because it is matched partially)

4
  • 4
    grepl('partial', 'I just want to partial match string')
    – Sotos
    Sep 13, 2019 at 14:35
  • Why do you want to use the %in% operator? this is exactly what grepl is for
    – MatthewR
    Sep 13, 2019 at 14:37
  • I am sorry, I am new to this. I saw %in% in few tutorials. Not sure difference between those two
    – user10272345
    Sep 13, 2019 at 14:53

3 Answers 3

4

Since you want to match partially from a sentence you should try using %like% from data.table, check below

library(data.table)
'I just want to partial match string' %like% 'partial'
 TRUE

The output is TRUE

1
`%in_str%` <- function(pattern,s){
  grepl(pattern, s)
}

Usage:

> 'a' %in_str% 'abc'
[1] TRUE
0
0

You need to strsplit the string so each word in it is its own element in a vector:

"partial" %in% unlist(strsplit('I just want to partial match string'," "))
[1] TRUE

strsplit takes a string and breaks it into a vector of shorter strings. In this case, it breaks on the space (that's the " " at the end), so that you get a vector of individual words. Unfortunately, strstring defaults to save its results as a list, which is why I wrapped it in an unlist - so we get a single vector. Then we do the %in%, which works in the opposite direction from the one you used: you're trying to find out if string partial is %in% the sentence, not the other way around.

Of course, this is an annoying way of doing it, so it's probably better to go with a grep-based solution if you want to stay within base-R, or Priyanka's data.table solution above -- both of which will also be better at stuff like matching multiple-word strings.

2
  • I do not follow this, bit advanced for my current understanding, yup will stick with above solution for now. Thank you much though
    – user10272345
    Sep 13, 2019 at 14:54
  • Added an explanation in my reply. Really not advanced stuff.
    – iod
    Sep 13, 2019 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.