Search code examples
rsubstr

Substring first character from right


I want to be able to substring the first character from the right hand side of each element of a vector

ABC20
BCD3
B1
AB2222
BX4444

so for the group above I would want, C, D, B, B, X .... is there an easy way to this? I know there is a substr and a numindex/charindex. So I think I can use these but not sure exactly in R.


Solution

  • You can use library stringi,

    stringi::stri_extract_last_regex(x, '[A-Z]')
    #[1] "C" "D" "B" "B" "X"
    

    DATA

    x <- c('ABC20', 'BCD3', 'B1', 'AB2222', 'BX4444')