0

Suppose I have two vectors of strings:

vec1 <- c("hellohi", "good", "goodafternoonabc")

vec2 <- c("helloworld", "goodmorning", "abc")

Is there a function that matches patterns within the two vectors, such that :

function(vec1, vec2) return matches : "hello", "good", "good", "abc" ? Thanks in advance.

Jaap
  • 81,064
  • 34
  • 182
  • 193

1 Answers1

-1

You can use %in% to check the matches, which creates a T F vector that can then be used for indexing against vec1.

vec1[vec1 %in% vec2]
Dan Raps
  • 308
  • 1
  • 7
  • 2
    This doesn't do what OP wants... returns `numeric(0)` in this case because none of the elements of vec1 are in vec2 (e.g. "hellohi" is not an element of vec2) – duckmayr Nov 09 '17 at 16:12
  • This is not a trivial problem and the solution will need to know what words are. – Roman Luštrik Nov 09 '17 at 16:15
  • 1
    @RomanLuštrik it looks more like just wanted to extract the longest possible matching string rather than actually knowing what words are. – MrFlick Nov 09 '17 at 16:17
  • Ahh yes, sorry about that - guess I didn't actually fully read what OP was looking for. – Dan Raps Nov 09 '17 at 20:53