How do I gsub an empty "" string in R?

John Waller picture John Waller · Mar 21, 2014 · Viewed 11k times · Source

How do I replace an empty string?

This:

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

produces:

"taco"      "tacobtaco"

instead of:

"taco"      "b"

Is there any way to replace an empty string?

Answer

agstudy picture agstudy · Mar 21, 2014

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"