93

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)

Wael
  • 1,640
  • 1
  • 9
  • 20
Zeeshan
  • 1,248
  • 1
  • 12
  • 19

3 Answers3

168

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)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 3
    @drmariod Yes, that is an alternative – akrun Jul 20 '15 at 13:49
  • 14
    Or use `fixed = TRUE` which doesn't use regex but instead just searches for the characters. `gsub(".", "-", x, fixed = T)` – Molx Jul 20 '15 at 14:47
  • 2
    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. – Mehdi Abbassi Feb 24 '20 at 12:53
  • 3
    @MehdiAbbassi You can do `gsub("[[:punct:]]", " ", x)` – akrun Feb 24 '20 at 17:18
6

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"
Wael
  • 1,640
  • 1
  • 9
  • 20
4

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

gsub(r"(\.)", "-", x)
# [1] "2014-06-09"
Maël
  • 45,206
  • 3
  • 29
  • 67