5

I would like to use str_detect and not convert "" to another string pattern. Is there an easy way to deal with empty string patterns "" which right now generates a warning. I would like this to produce TRUE, FALSE, FALSE, FALSE, FALSE

library( tidyverse )
str_detect('matt', c( "matt","joe","liz","", NA))
camille
  • 16,432
  • 18
  • 38
  • 60
MatthewR
  • 2,660
  • 5
  • 26
  • 37
  • just do it in the other way around `str_detect(c( "matt","joe","liz","", NA), 'matt')` if you really want the last element from output to be `FALSE` instead of `NA`, your input should be `c( "matt","joe","liz","", "NA")` , note `NA` inside `"`` – Jilber Urbina Mar 28 '19 at 14:49

4 Answers4

8

We can use

library(stringr)
library(tidyr)
str_detect(replace_na(v1, ''), 'matt')
#[1]  TRUE FALSE FALSE FALSE FALSE

If the match is not for a substring, then %in% would be useful

v1 %in% 'matt'
#[1]  TRUE FALSE FALSE FALSE FALSE

data

v1 <- c( "matt","joe","liz","", NA)
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662
6

If you're not tied to str_detect() perhaps try grepl()?

grepl("matt", c( "matt","joe","liz","", NA))

#[1]  TRUE FALSE FALSE FALSE FALSE
tomasu
  • 1,388
  • 9
  • 11
  • I prefer this one because it handles NAs better (str_detect won't return any rows that contain NAs) – flashton Sep 06 '22 at 07:21
2

Here is a way with package stringi the base of package stringr.

x <- c( "matt","joe","liz","", NA)
stringi::stri_detect_regex(x, 'matt') & !is.na(x)
#[1]  TRUE FALSE FALSE FALSE FALSE

The NA value must be tested, if not stri_detect_* will return NA.

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
2

You could also do-

v1 <- c( "matt","joe","liz","", NA)
sapply(v1, identical, "matt")

Output-

 matt   joe   liz        <NA> 
 TRUE FALSE FALSE FALSE FALSE 
Rushabh Patel
  • 2,672
  • 13
  • 34