2

Consider the following string:

"NIKE STORE COVENT GARDEN"

Suppose we are attempting to detect which is the brand that matches from the following vector:

brands <- c("ADIDAS", "NIKE", "PUMA", "COVENT", "CONVERSE")

Below is what I did with the resulting output:

library(stringr)
> brands[str_detect("NIKE STORE COVENT GARDEN", brands)]
[1] "COVENT"    "NIKE"

Clearly the brand here is "NIKE", and I know that it is consistently located before the location. Is there some way I can define a rule that in the case I detect multiple brands, that I select the one that appears earlier in the string?

NOTE: In the example above we conveniently have the brand name appear in the beginning of the string. However we sometimes have the case that the string we are considering is of the form "0123 NIKE STORE COVENT GARDEN"

7
  • which version of R and stringr are you using ? Commented Oct 22, 2015 at 14:13
  • R version 3.2.1; stringr version 1.0.0 Commented Oct 22, 2015 at 14:20
  • 1
    appart being with r 3.2.2, I got the correct integer output (not text), I suspect something in your R environment messing with it. You code as is return [1] 2 4 Commented Oct 22, 2015 at 14:23
  • @Tensibai you're right, sorry. I edited my question. Please consult the new version Commented Oct 22, 2015 at 14:25
  • As above, being used as selector or just the integer does not change anything. I still have a correct result (NIKE first) So I suspect brands is not in the order you think it is (maybe sorted before ? this would give this output) Commented Oct 22, 2015 at 14:28

1 Answer 1

2

You can consider using str_locate instead of str_detect. What about :

brands[which.min(str_locate("NIKE STORE COVENT GARDEN", brands)[,1])]
Sign up to request clarification or add additional context in comments.

1 Comment

Or in base, which(sapply(brands,grepl,x="NIKE STORE COVENT GARDEN"))[1]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.