Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling empty strings in string detection

Tags:

r

stringr

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))
like image 652
MatthewR Avatar asked Mar 28 '19 14:03

MatthewR


People also ask

What is the best way to test for an empty string in go?

In this shot, we will learn to check if a string is empty or not. In Golang, we can do this by: Comparing it with an empty string. Evaluating the length of the string; if it's zero, then the string is empty, and vice versa.

How do you test that a string str is the empty string?

Empty strings contain zero characters and display as double quotes with nothing between them ( "" ). You can determine if a string is an empty string using the == operator.

How do you fill an empty string in Python?

Strings are immutable in Python, you cannot add to them. You can, however, concatenate two or more strings together to make a third string.

Why do we use empty string in Python?

It is valid to have a string of zero characters, written just as '' , called the "empty string". The length of the empty string is 0. The len() function in Python is omnipresent - it's used to retrieve the length of every data type, with string just a first example.


2 Answers

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)
like image 104
akrun Avatar answered Oct 17 '22 01:10

akrun


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

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

#[1]  TRUE FALSE FALSE FALSE FALSE
like image 6
tomasu Avatar answered Oct 16 '22 23:10

tomasu