Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting the last n characters from a string in R

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

like image 753
Brani Avatar asked Nov 01 '11 08:11

Brani


People also ask

How do I extract the last few characters in a string in R?

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.

How do you get the last n characters of a string?

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.

How do you remove the last 4 characters on R?

Use the str_sub() Function to Remove the Last Characters in R.

How do you remove the last 5 characters on R?

Removing the last n characters To remove the string's last n characters, we can use the built-in substring() function in R.


2 Answers

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" 
like image 147
Andrie Avatar answered Oct 26 '22 14:10

Andrie


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" 
like image 34
Xu Wang Avatar answered Oct 26 '22 13:10

Xu Wang