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

Zak picture Zak · Jul 20, 2015 · Viewed 66.1k times · Source

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)

Answer

akrun picture akrun · Jul 20, 2015

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)