-5

I have an input text

   inputQ <- "What can I do ..my baby has rash all over. Suggest good rash cream"

I have a list of terms

terms <- c("diaper","cloth diaper","rash pants","rash","baby wipes","rash cream")

I wish to exact match one of the terms and return it as well I tried using for loop, but is there a better method

Result should be

 rash cream

stored in matchedTerm

Tarak
  • 1,035
  • 2
  • 8
  • 14
  • 1
    Why do you want "rash cream" but not "rash" returned? What did you try? – talat Feb 17 '17 at 08:16
  • *I wish to exact match one of the terms* ... which one? – Sotos Feb 17 '17 at 08:18
  • Possible duplicate of http://stackoverflow.com/questions/33856148/regex-in-r-extracting-words-from-a-string or http://stackoverflow.com/questions/33784376/extract-word-in-string-in-r – akrun Feb 17 '17 at 09:39

1 Answers1

5

You can try to get all the matches, then check for the one with the biggest number of characters:

wh_match <- names(unlist(sapply(terms, grep, inputQ)))
wh_match[which.max(nchar(wh_match))]
# [1] "rash cream"
Cath
  • 23,906
  • 5
  • 52
  • 86