Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

gsub

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] "           " "           " "           "
like image 647
star Avatar asked Feb 26 '16 15:02

star


1 Answers

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.

like image 87
2 revs Avatar answered Oct 17 '22 07:10

2 revs