Search code examples
stringrsubstringtrim

Retain last character in string with R


How can I obtain the last character of each string of various lengths?

[1] "3575742" "35752" "3541" ....

This would allow to drop the last character but how to retain/extract the character?

strtrim(df, nchar(df)-1)

So I would get only:

[1] "2" "2" "1" 

Solution

  • Perhaps you should look at substr instead:

    substr(x, nchar(x), nchar(x))
    # [1] "2" "2" "1"
    

    This is essentially, "Start at the last character and end at the last character".

    or...

    substring(x, nchar(x))
    # [1] "2" "2" "1"
    

    There's also a great package called "stringi" that has a lot of convenient string functions. For this problem, you can use stri_sub:

    library(stringi)
    stri_sub(x, -1)
    # [1] "2" "2" "1"