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)

3 Answers3

3

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
slava-kohut
  • 3,895
  • 1
  • 4
  • 21
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.

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