Home > OS >  How to remove some character of different length from end of a a string in R?
How to remove some character of different length from end of a a string in R?

Time:06-19

I want to remove every thing after second '_' and convert this vector

vec
[1] "HSC_bdl_HSC"                   "HSC_oil_HSC"                   "EC_oil_EC"                    
[4] "Chol (Sox9 )_ccl4_Chol (Sox9 )"

to

vec
    [1] "HSC_bdl"                   "HSC_oil"                   "EC_oil"                    
    [4] "Chol (Sox9 )_ccl4"

but I can't do that with gsub() or substr(). Thanks for any help.

CodePudding user response:

You may use sub here with the pattern _[^_]*$:

sub("_[^_]*$", "", x)
[1] "HSC_bdl"           "HSC_oil"           "EC_oil"           
[4] "Chol (Sox9 )_ccl4"

Data:

x <- c("HSC_bdl_HSC", "HSC_oil_HSC", "EC_oil_EC", "Chol (Sox9 )_ccl4_Chol (Sox9 )")
  •  Tags:  
  • r
  • Related