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

江枫思渺然 提交于 2019-12-19 07:09:10

问题


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?


回答1:


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"



回答2:


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.)




回答3:


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


来源:https://stackoverflow.com/questions/22565118/how-do-i-gsub-an-empty-string-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!