Oli Paul Oli Paul - 2 months ago 7
R Question

Gsub error [SOLVED - regex misunderstanding]

I don't seem to understand gsub or stringr.
Example:

> a<- "a book"

> gsub(" ", ".", a)

[1] "a.book"


Okay. BUT:

> a<-"a.book"

> gsub(".", " ", a)

[1] " "


I would of expected


"a book"


I'm replacing the full stop with a space.

Also:
srintr
:
str_replace(a, ".", " ")
returns:

" .book"


and
str_replace_all(a, ".", " ")
returns

" "


I can use
stringi
:
stri_replace(a, " ", fixed=".")
:

"a book"


I'm just wondering why gsub (and str_replace) don't act as I'd have expected. They work when replacing a space with another character, but not the other way around.

Answer

That's because the first argument to gsub, namely pattern is actually a regex. In regex the period . is a metacharacter and it matches any single character, see ?base::regex. In your case you need to escape the period in the following way:

gsub("\\.", " ", a)