简体   繁体   中英

How do I gsub an empty “” string in R?

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?

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"

I wouldn't use gsub here – semantically, I think of gsub as replacing parts within a string. For replacing a whole string, I would just use subsetting. And since you're searching for a fixed string ( '' ), it doesn't even need regular expressions:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM