Skip to content
Related Articles

Related Articles

Extracting Substrings from a Character Vector in R Programming – substring() Function

Improve Article
Save Article
Like Article
  • Last Updated : 27 Oct, 2021

substring() function in R Programming Language is used to extract substrings in a character vector. You can easily extract the required substring or character from the given string.

Syntax: substring(text, first, last)

Parameters: 

  • text: character vector
  • first: integer, the first element to be replaced
  • last: integer, the last element to be replaced

R – substring() Function Example

Example 1: Extracting values with substring function in R Programming language

R




# R program to illustrate
# substring function
 
# Calling substring() function
substring("Geeks", 2, 3)
substring("Geeks", 1, 4)
substring("GFG", 1, 1)
substring("gfg", 3, 3)

Output : 

[1] "ee"
[1] "Geek"
[1] "G"
[1] "g"

Example 2: Extracting values with substring in string function in R Programming language

R




# R program to illustrate
# substring function
 
# Initializing a string vector
x < - c("GFG", "gfg", "Geeks")
 
# Calling substring() function
substring(x, 2, 3)
substring(x, 1, 3)
substring(x, 2, 2)

Output: 

[1] "FG" "fg" "ee"
[1] "GFG" "gfg" "Gee"
[1] "F" "f" "e"

Example 3: String replacement in R using substring() function

R




# R program to illustrate
# substring function
 
# Initializing a string vector
x <- c("GFG", "gfg", "Geeks")
 
# Calling substring() function
substring(x, 2, 3) <- c("@")
print(x)

Output:

[1] "G@G"   "g@g"   "G@eks"

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!