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

Another reasonably straightforward way is to use regular expressions and sub:

sub('.*(?=.$)', '', string, perl=T)

So, "get rid of everything followed by one character". To grab more characters off the end, add however many dots in the lookahead assertion:

sub('.*(?=.{2}$)', '', string, perl=T)

where .{2} means .., or "any two characters", so meaning "get rid of everything followed by two characters".

sub('.*(?=.{3}$)', '', string, perl=T)

for three characters, etc. You can set the number of characters to grab with a variable, but you'll have to paste the variable value into the regular expression string:

n = 3
sub(paste('.+(?=.{', n, '})', sep=''), '', string, perl=T)

Examples related to r

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R? R : how to simply repeat a command? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium How to show code but hide output in RMarkdown? remove kernel on jupyter notebook Function to calculate R2 (R-squared) in R Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph R multiple conditions in if statement What does "The following object is masked from 'package:xxx'" mean?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to substring

Go test string contains substring How does String substring work in Swift Delete the last two characters of the String Split String by delimiter position using oracle SQL How do I check if a string contains another string in Swift? Python: Find a substring in a string and returning the index of the substring bash, extract string before a colon SQL SELECT everything after a certain character Finding second occurrence of a substring in a string in Java Select query to remove non-numeric characters