Home > Software engineering >  Filter str_detect does not equal
Filter str_detect does not equal

Time:04-19

I'm attempting to filter for values of a character variable var that do not contain a period (.) within them. I'm trying something like:

d <- d %>% 
  filter(
    str_detect(var, !".")
  )

But that doesn't seem to work. I assume this is an easy fix but I can't quite figure it out.

CodePudding user response:

str_detect searches for matches using regular expressions, and in regular expressions . means "any character". You'll need to use \\. so that the period is recognized literally. And your negation is in the wrong place:

d %>% 
    filter(
        !str_detect(var, "\\.")
    )

str_detect also has a "negate" argument that returns results that do not match the provided pattern. This is equivalent to the above:

d %>% 
    filter(
        str_detect(var, "\\.", negate = T)
    )
  • Related