0

I am dealing with the following strings:

 "I(x - lambda * WX)(Intercept)"                     "I(x - lambda * WX)pres_dem_two_party_vote_percent"
 "I(x - lambda * WX)dem_seat"                        "I(x - lambda * WX)forgnpct"                       
 "I(x - lambda * WX)blackpct"                        "I(x - lambda * WX)log_people_per_mi2"    

I would like to remove : I(x - lambda * WX) from the string so that all that is left is:

"(Intercept)"                     "pres_dem_two_party_vote_percent"
"dem_seat"                        "forgnpct"                       
"blackpct"                        "log_people_per_mi2"    

I have tried to use gsub and str_replace, with no success.

Any help you could offer, I would be grateful. Thanks so much!

Sharif Amlani
  • 1,138
  • 1
  • 11
  • 25

1 Answers1

2

Since you have some special characters in the string to remove use fixed = TRUE in sub

sub("I(x - lambda * WX)", "", x, fixed = TRUE)

#[1] "(Intercept)"                     "pres_dem_two_party_vote_percent"
#[3] "dem_seat"                        "forgnpct"                       
#[5] "blackpct"                        "log_people_per_mi2"   

Or escape all the special characters

sub("I\\(x - lambda \\* WX\\)", "", x)

data

x <-  c("I(x - lambda * WX)(Intercept)",
        "I(x - lambda * WX)pres_dem_two_party_vote_percent",
        "I(x - lambda * WX)dem_seat" ,"I(x - lambda * WX)forgnpct",
        "I(x - lambda * WX)blackpct",  "I(x - lambda * WX)log_people_per_mi2" )      
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Wow, I didn't know that was an option and that special characters inside the string need to be treated differently. Thank you so much for your help! I really appreciate and I learned something new. – Sharif Amlani Sep 19 '19 at 00:40
  • For those using regex, the code to refer to a "(" is "\\("). – Sharif Amlani Nov 25 '19 at 00:00