stringr::str_sub("abcdefgh", 3, 5)[1] "cde"
The function stringr::str_sub() allows you to extract sub strings from strings. The function requires three arguments:
The positions are integers/whole numbers and are inclusive.
Additionally, this function can be used to replace the specified strings.
Substrings can be extracted from scalars.
Extract position 3:5 in one string (i.e. a scalar).
One character can be extracted by setting the start and end positions to the same integer.
Providing an end position longer than the vector will still work, only providing the characters from the specified start position to the end of the vector.
Below we specify 7 to 10 on 8 length string and we are provided characters 7-8.
You can use negative numbers to represent a position relative to the end. For example, -4 would mean the 4th-to-last character and -2 would represent the 2nd-to-last character.
Extract the fourth last to the 2nd last characters.
This means you can use -1 to represent the last character.
Extract the 6th to last character.
If our start position is higher than our end position we extract nothing.
Any of the above methods can be used on a vector of strings. With a vector the function acts on each string separately.
First create a vector.
Extract the 2nd to 3rd positions.
Extract the 2nd to 10th position.
Extract the 2nd to the last position
Extract the first to the third last position.
Extract the 10th to the 15th position.
str_sub() can be used to modify strings by replacing the characters of the specified positions.
This can be carried out by running the function followed by an assignment operator (<-) with the string fro replacement.
Replace the last two characters with “re”
[1] │ sabre
The replacement does not need to have the same number of characters as the original substring.
Replace the fourth character with “ou”.
[1] │ colour
You can remove a substring by replacing with nothing (i.e. "").
[1] │ burgled
This works with vectors too.