SPS
SPS

Reputation: 127

How to filter Exact match string using dplyr

I have datatable datatmp

    datatmp
        Code         Desc
       Z00.1 Description1
         Z00 Description2
         Z38 Description3
       Z38.0 Description4
       Z38.1 Description5

Try to filter only Z38 code using

datatmp %>% dplyr::filter(str_detect(Code,'Z38'))

But get the below result which incl. Z38.0 and Z38.1

   Code         Desc
    Z38 Description3
  Z38.0 Description4
  Z38.1 Description5

Also tried with datatmp %>% dplyr::filter(grepl('Z38',Code,fixed = TRUE)) gives sample output.

Note: The above example I mentioned only one value i.e. Z38 in the filter condition , actually these values are dynamic. Example Z38 , Z00

Please suggest to find exact match only.

Upvotes: 3

Views: 4871

Answers (1)

tricky999
tricky999

Reputation: 391

You were close with your grepl filter. Change the code to:

datatmp %>% dplyr::filter(grepl("^Z38$", Code))

The ^ symbol denotes the start of the string (technically not necessary in this case) and the $ symbol denotes the end of the string, so Z38.0 would not match.

Upvotes: 4

Related Questions