Amit Verma
Amit Verma

Reputation: 95

Replacing a character string in R

I am trying to remove/replace a certain part in the character strings.

Data:

b <- "Brunswick North Brunswick (Vic.) Bellfiled (Banyule - Vic.)"

I would like the result to look like:

"Brunswick North Brunswick Bellfield"

I have tried doing:

sub("(Vic.)", "", b, fixed = TRUE)

By doing so, I get the required output for the second element i.e. "Brunswick" but not for the third element.

Upvotes: 1

Views: 80

Answers (2)

CuriousBeing
CuriousBeing

Reputation: 1632

If you want to replace everything that is inside the parantheses then try this. This will remove the brackets and everything inside it.

gsub("\\s*\\([^\\)]+\\)","",b)

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174874

Use gsub

gsub("\\([^)]*Vic\\.\\)", "", b) 

Upvotes: 2

Related Questions