Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep the last 9 digits of an alphanumeric string in R

Tags:

r

Please R-gurus, how can I keep the last 9 digits of an alphanumeric string for e.g.

LA XAN 000262999444
RA XAN 000263000507
WA XAN 000263268038
SA XAN 000263000464
000263000463
000263000476

I only want to get

262999444
263000507
263268038
263000464
263000463
263000476

Thanks a lot

like image 280
nolyugo Avatar asked Aug 30 '11 20:08

nolyugo


2 Answers

It's pretty easy in stringr because sub_str interprets negative indices as offsets from the end of the string.

library(stringr)
str_sub(xx, -9, -1)
like image 79
hadley Avatar answered Oct 26 '22 06:10

hadley


If you just want the last 9 positions, you could just use substr:

substr(xx,nchar(xx) - 8,nchar(xx))

assuming that your character vector is stored in xx. Also, as Hadley notes below, nchar will return unexpected things if xx is a factor, not a character vector. His solution using stringr is definitely preferable.

like image 26
joran Avatar answered Oct 26 '22 05:10

joran