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"
Related videos on Youtube
Comments
-
Zeeshan over 2 years
I want to replace dots in
"2014.06.09"
to"2014-06-09"
. I am using gsub() function for it. Ifx <- "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 almost 9 years@drmariod Yes, that is an alternative
-
Molx almost 9 yearsOr use
fixed = TRUE
which doesn't use regex but instead just searches for the characters.gsub(".", "-", x, fixed = T)
-
Mehdi Abbassi about 4 yearswhat 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 about 4 years@MehdiAbbassi You can do
gsub("[[:punct:]]", " ", x)