How can I delete an empty string in R?

How to replace an empty string?

It:

x = c("","b") gsub("","taco",x) 

produces:

 "taco" "tacobtaco" 

instead:

 "taco" "b" 

Is there a way to replace an empty string?

+6
source share
3 answers

I would use nchar here:

  x[nchar(x)==0] <- "taco" 

EDIT

If you are looking for performance, so you should use nzchar:

 x[!nzchar(x)] <- "taco" 
+11
source

I would not use gsub here - semantically, I think of gsub as replacing parts within a string. To replace an entire string, I would just use a subset. And since you're looking for a fixed string ( '' ), it doesn't even need regular expressions:

 x[x == ''] = 'taco' 

(Of course, this reassigns the original vector x , while gsub just returns the modified result.)

+3
source
 x = c("","b") gsub("^$","taco",x) 
+2
source

All Articles