Home > Software engineering >  Keep all columns when using gsub
Keep all columns when using gsub

Time:07-31

I have a dataset LonGB which contain the following dataframe:

Number   City     Street    Av.Cost
1       London     Ap (U)     550
2       London     Up         450
3       London     Ar         350
4       London     Tr (M)     250
5       London     Ar         545
6       London     Sl         530
7       London     Qr         520
8       London     Re (N)     510
9       London     Ra         480
#With 58 more rows

I want first to remove the symbols within brackets as the code to the right does gsub("\\s*\\([^\\)] \\)","",as.character(LonGB$Street)) which gives the following tibble:

Street
Ap
Up
Ar
Tr
Ar
Sl
Qr
Re
Ra
#With 58 more rows

However, I don't want just the street column but the whole dataset just without the symbols within brackets, like this:

Number   City     Street    Av.Cost
1       London     Ap         550
2       London     Up         450
3       London     Ar         350
4       London     Tr         250
5       London     Ar         545
6       London     Sl         530
7       London     Qr         520
8       London     Re         510
9       London     Ra         480
#With 58 more rows

How do I do that?

CodePudding user response:

Just use this

LonGB$Street <- gsub("\\s*\\([^\\)] \\)","",as.character(LonGB$Street))

CodePudding user response:

library(dplyr) ; LonGB %>% mutate(Street = gsub("\\s*\\ ([^\\)] \\)","",as.character(LonGB$Street)))

The following code brought by @gaut solved my task.

CodePudding user response:

We can use:

library(dplyr)
LonGB %>% mutate(Street = gsub("\\s*\\ ([^\\)] \\)","",as.character(Street)))

or in base R

LonGB$Street <- gsub("\\s*\\ ([^\\)] \\)","",as.character(LonGB$Street))

You are just replacing the Street column.

  •  Tags:  
  • r
  • Related