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"
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.