How can I get the last n characters from a string in R? Is there a function like SQL's RIGHT?
To get the last n characters from a string, we can use the stri_sub() function from a stringi package in R. The stri_sub() function takes 3 arguments, the first one is a string, second is start position, third is end position.
To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string. Copied! const str = 'Hello World'; const last3 = str.
Use the str_sub() Function to Remove the Last Characters in R.
Removing the last n characters To remove the string's last n characters, we can use the built-in substring() function 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With