R-substr, substring

Retrieve or replace a substring of a character string via the substr and substringfunctions. Additionally, these functions can be used to overwrite a part of a character string.

substr(x, start, stop)
  • x – A character string.
  • start – If the characters of x were numbered, then the number of the first character to be returned (or overwritten).
  • stop – The number of the last character to be returned (or overwritten).
substring(x, first, last=1000000)
  • x – A character string.
  • first – If the characters of x were numbered, then the number of the first character to be returned (or overwritten).
  • last – The number of the last character to be returned (or overwritten), which is defaulted to 1 million.

 

Example. Below are several simple examples of using substr. Notice in the last example of substr, where I try to extend the string out past its original length, does not work in this way. The string length cannot be changed using substr. Notice that thesubstring function has a default setting for the third argument.
> x <- "1234567890"
> substr(x, 3, 3)
[1] "3"
> 
> substr(x, 5, 7)
[1] "567"
> 
> substr(x, 4, 4) <- "A"
> x
[1] "123A567890"
> 
> substr(x, 2, 4) <- "TTF"
> x
[1] "1TTF567890"
> 
> substr(x, 9, 12) <- "ABCD"
> x
[1] "1TTF5678AB"
> 
> substring(x, 5)
[1] "5678AB"
> 
> substring(x, 5) <- "..."
> x
[1] "1TTF...8AB"
The substring function is a little more robust than substr.