Skip to main content
2 of 2
added 257 characters in body
effel
  • 1.4k
  • 1
  • 9
  • 17

The error is from misplaced parentheses, so these minor variations on your code will work.

L[grep(paste(id1,id2,sep=""), L)]
# character(0)
L[grep(paste(id2,id1,sep=""), L)]
# [1] "catdog"

Alternatively this is a regex one-liner:

L[grep(paste0(id2, id1, "|", id1, id2), L)]
# [1] "catdog"

That and some patterns in the comments will also match dogcatt. To avoid this you could use ^ and $ like so:

x <- c("dogcat", "foo", "catdog", "ddogcatt")
x[grep(paste0("^", id2, id1, "|", id1, id2, "$"), x)]
# [1] "dogcat" "catdog"
effel
  • 1.4k
  • 1
  • 9
  • 17