Reputation: 4229
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"
Upvotes: 1
Views: 6409
Reputation: 12569
Here is a solution with regular expressions:
x <- c("3575742", "35752", "3541")
sub("^.*(.)$", "\\1", x)
# [1] "2" "2" "1"
Upvotes: 1
Reputation: 193657
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"
Upvotes: 13