replace "." with space using gsub() in R?

star picture star · Feb 26, 2016 · Viewed 30.2k times · Source

I have data as below, I like to replace "." with space using gsub() but I could not get correct output.

data<-c("12.57869486" ,"12.57869582" ,"12.57870155")

a<- gsub("."," ", data)
a
[1] "           " "           " "           "

Answer

Tensibai picture Tensibai · Feb 26, 2016

Many way to achieve this:

1) Use the fixed parameter of gsub:

From ?gsub:

fixed logical. If TRUE, pattern is a string to be matched as is. Overrides all conflicting arguments.

So adding fixed=TRUE to your command is enough to avoid intepreting the . as any character (regex mode):

> a<-gsub(".", " ", data, fixed=TRUE)
> a
[1] "12 57869486" "12 57869582" "12 57870155"

2) Use chartr (from G. Grothendieck comment):

chartr(".", " ", data)

3) Escape the special char . which mean any character in regex: (from Tim Biegeleisen comment)

  • gsub("\\.", " ", data) Escape with a double backslash
  • gsub("[.]", " ", data) Escape using character class

In long regex I tend to prefer the second syntax as I find it more readable.