Extracting the last n characters from a string in R

Brani picture Brani · Nov 1, 2011 · Viewed 349.3k times · Source

How can I get the last n characters from a string in R? Is there a function like SQL's RIGHT?

Answer

Andrie picture Andrie · Nov 1, 2011

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"