a_todd12
a_todd12

Reputation: 550

Filter str_detect does not equal

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.

Upvotes: 1

Views: 1229

Answers (1)

jdobres
jdobres

Reputation: 11957

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)
    )

Upvotes: 3

Related Questions