Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove n last character from a string

Tags:

string

r

gsub

I would like to remove the third and fourth last character from as string.

Here is some sample data:

HS0202
HS0902
MV0100
SUE0300

I would need return something like this

HS02
HS02
MV00
SUE00
like image 447
C K Avatar asked Nov 23 '25 17:11

C K


2 Answers

Using a regex with gsub():

gsub("..(?=..$)", "", chrs, perl = TRUE)
# "HS02"  "HS02"  "MV00"  "SUE00"

Or with stringr::str_remove():

library(stringr)

str_remove(chrs, "..(?=..$)")
# "HS02"  "HS02"  "MV00"  "SUE00"
like image 126
zephryl Avatar answered Nov 26 '25 10:11

zephryl


You can extract from first to fourth last characters, and paste on the final character as follows:

have <- c('HS0202', 'HS0902', 'MV0100', 'SUE0300')

want <- paste0(substring(have,1,nchar(have)-3),substring(have,nchar(have)))
like image 20
shaun_m Avatar answered Nov 26 '25 11:11

shaun_m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!