gsub() in R is not replacing '.' (dot)

我们两清 提交于 2019-12-17 09:33:16

问题


I want to replace dots in "2014.06.09" to "2014-06-09". I am using gsub() function for it. If

x <-  "2014.06.09"
gsub('2', '-' ,x)
# [1] "-014.06.09"

But when I try

gsub('.', '-', x)
# [1] "----------"

instead of "2014-06-09".

class(x)
# "character"

Can some suggest me a way to get this right and also why it is not working for '.' (dot)


回答1:


You may need to escape the . which is a special character that means "any character" (from @Mr Flick's comment)

 gsub('\\.', '-', x)
 #[1] "2014-06-09"

Or

gsub('[.]', '-', x)
#[1] "2014-06-09"

Or as @Moix mentioned in the comments, we can also use fixed=TRUE instead of escaping the characters.

 gsub(".", "-", x, fixed = TRUE)


来源:https://stackoverflow.com/questions/31518150/gsub-in-r-is-not-replacing-dot

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