-1

Been trying to use gsub to replace a "+" with a " " and instead it adds a space between every second letter.

> "the+internet" 
gsub(pattern = "+",replacement = " ", data1)
> " t h e + i n t e r n e t "

Instead of course I'd want;

> "the internet"

Also after this issue is resolved, what method could I use to capitalise every first letter of a word?

Cheers.

Ronak Shah
  • 286,338
  • 16
  • 97
  • 143
srb633
  • 541
  • 3
  • 9

1 Answers1

1

+ has a special meaning in regex so you need to escape it (with \\) or use fixed = TRUE. You can then use tools::toTitleCase to capitalize the first letter of every word.

tools::toTitleCase(sub('+',' ', 'the+internet', fixed = TRUE))
#[1] "The Internet"
Ronak Shah
  • 286,338
  • 16
  • 97
  • 143
  • Probably a duplicate. – Tim Biegeleisen Mar 28 '20 at 04:52
  • 1
    @TimBiegeleisen If it was just `+`, then yes I would have marked it with https://stackoverflow.com/questions/27721008/how-do-i-deal-with-special-characters-like-in-my-regex but OP also wanted to capitalize the first letter in every word, hence I answered. I don't agree with the duplicate post that you have marked this with because that post is way too general for anybody to find any meaningful answer to their specific regex quesion. Also, you could probably mark it as a duplicate of every `regex` question with that post then. Although, this is only my opinion. – Ronak Shah Mar 28 '20 at 04:56