Reputation: 438
I am trying to remove the last trailing underscore(_) from a string using R.
For example,
Col1
TX_
AZ_TX
CA_LX
CHI_
KS_
The above strings should look like
Col1
TX
AZ_TX
CA_LX
CHI
KS
Only the trailing _ be gone. I tried sub("_", "", my_dataframe$my_column)
but this removes all the _ from the string. I am just looking for a function that removes the last trailing _ and not all. Any ideas ?
Upvotes: 5
Views: 4126
Reputation: 7445
You can use sub
(or gsub
) with the regular expression "_$"
to find the _
at the end of the input, then replace with ""
:
s <- c('Col1', 'TX_', 'AZ_TX', 'CA_LX', 'CHI_', 'KS_')
sub("_$","",s)
##[1] "Col1" "TX" "AZ_TX" "CA_LX" "CHI" "KS"
Upvotes: 7