Substring Function in R

The substring function in R can be used either to extract parts of character strings, or to change the values of parts of character strings

syntax for Substring function in R: 

substr(text, start, stop)
substring(text, first, last = 1000000L)
  • First Argument (Text) is the string,
  • second argument (start/first)  is start position of the substring
  • Third argument(stop/last) is end position of the substring

Extracting values with substring function in R:

Lets see an example to extract values using substring function in R.

## Extracting values with substring in R

substring("HumptyDumpty sat on a wall",5,9)

when we execute the above code, string staring from the 5th letter to 9th letter is extracted as a substring, so the output will be

[1] “tyDum”

Replacing values with substring function in R:

Substring function in R is not just used for extraction, but also used for replacing the part of substring. lets see with help of an example

## Replacing values with substring in R

mystring<-"Humpty_Dumpty sat on a wall"
substring(mystring,7,7)=" "

when we execute the above code the underscore(_) is replaced with space(“ ”). So the output will be

“[1] Humpty Dumpty sat on a wall”


Lets see an another example with recycling replacement

## Replacement with recycling

z = c("may", "the", "rain", "shower")
substring(z, 2, 3) <- c("@", "#")

in the above example, substring function replaces every second letter with @ and # consecutively. So the output will be

[1] “m@y”    “t#e”    “r@in”   “s#ower”

previous small substring function in R                                                                                                                next small substring function in R