Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove certain elements form string

Tags:

r

rstudio

So I have vector which consist of

data<-c("Mark And (BD Marketing Da 1 Z _ 9793)",
"Andre All (BD Marketing DA 1 Z _ 9794 (plus))", 
"Alli Inn (BD Sport Educ 1 C _ 9722 (plus))",
"Alli Inn (BP Sport Educ 1 Z _ 9347)")

And now I need to remove all characters up to _ and also both parenthesis where it is missing the word (plus) so the outcome should be

Mark And BD Marketing Da 1 Z
Andre All BD Marketing DA 1 Z (plus)
Alli Inn BD Sport Educ 1 C (plus)
Alli Inn BP Sport Educ 1 Z

I used gsub("\\s*\\w*$", "", data) and got

Alli Inn (BP Sport Educ 1 Z

but this is not correct as I need to remove other parenthesis and also keep (plus) where it is written.

I have tried this: gsub('\((?!plus)|(?<!plus)\)|.\\d+', '', rownames(data), perl=TRUE) and got this Alli Inn BP Sport Educ Z but now I am missing number 1 before letter

like image 859
Miha Avatar asked Jul 30 '26 16:07

Miha


1 Answers

gsub('\\((?!plus)|(?<!plus)\\)|_ [0-9]*', '', data, perl=TRUE)
#[1] "Mark And BD Marketing Da 1 Z "        
#[2] "Andre All BD Marketing DA 1 Z  (plus)"
#[3] "Alli Inn BD Sport Educ 1 C  (plus)"   
#[4] "Alli Inn BP Sport Educ 1 Z " 
like image 129
Pierre L Avatar answered Aug 01 '26 07:08

Pierre L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!