user6108949 user6108949 - 3 months ago 11
R Question

Remove first occurrence of underscore in a string

I have a character string of names which look like

"_6302_I-PAL_SPSY_000237_001"


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

"6302_I-PAL_SPSY_000237_001"


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

Answer

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"

data

str1 <- "_6302_I-PAL_SPSY_000237_001"
Comments