Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 314
Zeeshan Avatar asked Jul 20 '15 13:07

Zeeshan


People also ask

How do I remove the dot from a string in R?

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.

What does GSUB return in R?

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.

How do I replace nothing in R?

Use gsub in R to remove / and replace with nothing.


2 Answers

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) 
like image 133
akrun Avatar answered Nov 09 '22 14:11

akrun


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" 
like image 23
Wael Avatar answered Nov 09 '22 14:11

Wael