Oli Paul Oli Paul - 1 year ago 105
R Question

Gsub error [SOLVED - regex misunderstanding]

I don't seem to understand gsub or stringr.

> 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.

str_replace(a, ".", " ")

" .book"

str_replace_all(a, ".", " ")

" "

I can use
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 Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download