0

Given a list of vectors:

x <- list(c("street_address", "poi", "point"), c("route", "interest", "point_of_interest"))
x

[[1]]
[1] "street_address" "poi"            "point"         

[[2]]
[1] "route"             "interest"          "point_of_interest"

.. I' like to use stringr::str_which (which is a wrapper of which around str_detect) to detect the vector which contains an exact match of a given word.

Example:

str_which(x, "poi")

returns

[1] 1 2

because (as far as I understand it) "poi" is both contained in "poi" and "point" of the first vector, but also in "point_of_interest" of the second vector.

That's why I used anchors, like so:

str_which(x, "^poi$")

But this returns:

integer(0)

So, anchors don't seem to work. What to do here?

grssnbchr
  • 2,877
  • 7
  • 37
  • 71
  • Not sure how to get it with `str_which`, but is it ok to sapply grep as a workaround? `which(sapply(z, function(j)length(grep("^poi$",j)>0))>0)` ? – steveLangsford May 16 '18 at 16:59
  • You don't need to use reg exes: `which(sapply(x, function(z) any(z %in% "poi")))` – Brian Davis May 16 '18 at 17:09
  • @BrianDavis Nice solution to this concrete problem. I figure `which(sapply(x, function(z)("poi" %in% z)))` without the `any` call would actually be enough. However, I'm still interested in a `stringr`-solution. – grssnbchr May 16 '18 at 19:41
  • Maybe you want `sapply(x, function(z) str_which('^poi$', z))`? Note that acc. to the function help, *`str_which()` is a wrapper around `which(str_detect(x, pattern))`, and is equivalent to `grep(pattern, x)`*. – Wiktor Stribiżew May 16 '18 at 19:48
  • `str_which(x, "poi")` is the correct solution. The problem is with the class of your input x. You have passed list but str_which accepts vectors. You can modify it to vector type and pass it as input. – M L May 17 '18 at 05:57
  • How about `grep("\\bpoi\\b", x)` – Rich Scriven May 18 '18 at 12:24

0 Answers0