Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

gsub

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?

like image 556
John Waller Avatar asked Mar 21 '14 17:03

John Waller


2 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"
like image 114
agstudy Avatar answered Sep 21 '22 02:09

agstudy


x = c("","b")
gsub("^$","taco",x)
like image 35
John Waller Avatar answered Sep 19 '22 02:09

John Waller