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.
substr(s, start, stop)
- 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.
s <- "This is patrnous charm" substr(s, start = 9, stop = 16)
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)
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)
That is it for the R substr() method.