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

RRegexGsubStringr

R Problem Overview


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)

R Solutions


Solution 1 - R

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)

Solution 2 - R

For more complex tasks the stringr package could be interesting

https://cran.r-project.org/web/packages/stringr/vignettes/stringr.html

https://github.com/rstudio/cheatsheets/raw/master/strings.pdf

library(stringr)

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

Or

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

Solution 3 - R

Using raw strings, introduced in R 4.0.0, one could do

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZeeshanView Question on Stackoverflow
Solution 1 - RakrunView Answer on Stackoverflow
Solution 2 - RWaelView Answer on Stackoverflow
Solution 3 - RMaëlView Answer on Stackoverflow