Extracting the last n characters from a string in R Extracting the last n characters from a string in R r r

Extracting the last n characters from a string in R


I'm not aware of anything in base R, but it's straight-forward to make a function to do this using substr and nchar:

x <- "some text in a string"substrRight <- function(x, n){  substr(x, nchar(x)-n+1, nchar(x))}substrRight(x, 6)[1] "string"substrRight(x, 8)[1] "a string"

This is vectorised, as @mdsumner points out. Consider:

x <- c("some text in a string", "I really need to learn how to count")substrRight(x, 6)[1] "string" " count"


If you don't mind using the stringr package, str_sub is handy because you can use negatives to count backward:

x <- "some text in a string"str_sub(x,-6,-1)[1] "string"

Or, as Max points out in a comment to this answer,

str_sub(x, start= -6)[1] "string"


Use stri_sub function from stringi package.To get substring from the end, use negative numbers.Look below for the examples:

stri_sub("abcde",1,3)[1] "abc"stri_sub("abcde",1,1)[1] "a"stri_sub("abcde",-3,-1)[1] "cde"

You can install this package from github: https://github.com/Rexamine/stringi

It is available on CRAN now, simply type

install.packages("stringi")

to install this package.