Question

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" 
Was it helpful?

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"

OTHER TIPS

Here is a solution with regular expressions:

x <- c("3575742", "35752", "3541")
sub("^.*(.)$", "\\1", x)
# [1] "2" "2" "1"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top