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

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

data<-c("12.57869486" ,"12.57869582" ,"12.57870155") a<- gsub("."," ", data) a [1] " " " " " " 
+5
source share
1 answer

Many ways to achieve this:

1) Use the fixed gsub parameter:

From ?gsub :

fixed boolean. If TRUE, the pattern is a string that will match as is. Overrides all conflicting arguments.

Thus, adding fixed=TRUE to your command is enough to avoid intepreting. like any character (regular expression mode):

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

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

 chartr(".", " ", data) 

3) Escape from a special char . , which means any character in the regular expression: (from a comment by Tim Bigeleisen)

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

In a long regular expression, I prefer the second syntax because I find it more readable.

+8
source

Source: https://habr.com/ru/post/1243952/


All Articles