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))
1
  • 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 `"`` Commented Mar 28, 2019 at 14:49

4 Answers 4

9

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)
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

I prefer this one because it handles NAs better (str_detect won't return any rows that contain NAs)
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.

Comments

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.