To retrieve or replace a character string substring in R, use the substr() method. To extract the substring of the column in R, use the functions like substr() and substring().
substr() in R
The substr() is a built-in R method that returns the substrings of a character vector. It extracts or replaces substrings in a character vector. The substring() function in R can be used either to extract elements of character strings or to change parts of character strings. The substring of a vector or column in R can be extracted using the substr() function.
Syntax
substr(s, start, stop)
Parameters
- s: It is a character string.
- start: If the characters of s were numbered, then the first character would be returned.
- stop: The number of the last character to be returned.
Example
s <- "This is patrnous charm"
substr(s, start = 9, stop = 16)
Output
[1] "patrnous"
In this example, we specified a starting (9) and a finishing point (16), between which we extracted all letters of our string object s.
Character Vector from Certain Position to the Right
If you want to print strings from certain characters, you can use the substr() method.
s <- "This is patrnous charm"
substr(s, start = 9)
Output
Error in substr(s, start = 9) :
argument "stop" is missing, with no default
Execution halted
We get the Error: argument “stop” is missing, with no default
Extract Multiple Substrings
If we apply the substr() function to several starting or stopping points, the function uses only the first entry (for example, the stopping point 1).
s <- "This is patrnous charm"
substr(s, start = 1, stop = 1:5)
Output
[1] "T"
That is it for the R substr() method.
See also

Krunal Lathiya is an Information Technology Engineer by education and web developer by profession. He has worked with many back-end platforms, including Node.js, PHP, and Python. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language. Krunal has written many programming blogs, which showcases his vast expertise in this field.