user6108949 user6108949 - 5 months ago 18
R Question

Remove first occurrence of underscore in a string

I have a character string of names which look like


I need to remove the first occurred underscore, so that it will be as


I aware of
but it removes all of underscores. Thank you for any suggestions.


We can use sub with pattern as _ and replacement as blanks (""). This will remove the first occurrence of '_'.

sub("_", "", str1)
#[1] "6302_I-PAL_SPSY_000237_001"

NOTE: This will remove the first occurence of _ and it will not limit based on the position i.e. at the start of the string.

For example, suppose we have string

str2 <- "6302_I-PAL_SPSY_000237_001"
sub("_", "", str2)
#[1] "6302I-PAL_SPSY_000237_001"

As the example have _ in the beginning, another option is substring

substring(str1, 2)
#[1] "6302_I-PAL_SPSY_000237_001"


str1 <- "_6302_I-PAL_SPSY_000237_001"