MatthewR
MatthewR

Reputation: 2770

Handling empty strings in string detection

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

Upvotes: 5

Views: 5016

Answers (4)

akrun
akrun

Reputation: 887691

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)

Upvotes: 9

Rushabh Patel
Rushabh Patel

Reputation: 2764

You could also do-

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

Output-

 matt   joe   liz        <NA> 
 TRUE FALSE FALSE FALSE FALSE 

Upvotes: 2

tomasu
tomasu

Reputation: 1438

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

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

#[1]  TRUE FALSE FALSE FALSE FALSE

Upvotes: 6

Rui Barradas
Rui Barradas

Reputation: 76621

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.

Upvotes: 2

Related Questions