Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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+)")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading