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

92,368

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

Solution 2

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"
Share:
92,368

Related videos on Youtube

Zeeshan
Author by

Zeeshan

Data Science | Visualization | Statistics

Updated on January 26, 2022

Comments

  • Zeeshan
    Zeeshan over 2 years

    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)

  • akrun
    akrun almost 9 years
    @drmariod Yes, that is an alternative
  • Molx
    Molx almost 9 years
    Or use fixed = TRUE which doesn't use regex but instead just searches for the characters. gsub(".", "-", x, fixed = T)
  • Mehdi Abbassi
    Mehdi Abbassi about 4 years
    what if we want to change every single punctuation signs with something else like space? In dealing with texts from social media or reviews I come up with a lot of dots or other punctuation signs between words, because the forgot to use space after they finish the sentence.
  • akrun
    akrun about 4 years
    @MehdiAbbassi You can do gsub("[[:punct:]]", " ", x)