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)
To remove dot and number at the end of the string, we can use gsub function. It will search for the pattern of dot and number at the end of the string in the vector then removal of the pattern can be done by using double quotes without space.
gsub() function in R Language is used to replace all the matches of a pattern from a string. If the pattern is not found the string will be returned as it is.
Use gsub in R to remove / and replace with nothing.
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)
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With