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

substring() Function in detail

The substring() function in R programming is used to extract substrings from a character vector. It allows you to extract specific substrings or characters from the provided string easily.

Syntax:

substring(text, first, last)

Parameters:

  • text: Character vector.
  • first: Integer, specifying the starting position of the substring.
  • last: Integer, specifying the ending position of the substring.

Example 1: Extracting values with substring() function in R

# R program to demonstrate
# the substring() function

# Extracting substrings
substring("Hello", 2, 4)
substring("World", 1, 3)
substring("R", 1, 1)
substring("data", 4, 4)

Output:

[1] "ell"
[1] "Wor"
[1] "R"
[1] "a"

Example 2: Using substring() on a character vector

# R program to demonstrate
# substring function on a vector

# Initializing a character vector
vec <- c("Code", "data", "Analysis")

# Extracting substrings
substring(vec, 2, 3)
substring(vec, 1, 4)
substring(vec, 3, 3)

Output:

[1] "od" "at" "na"
[1] "Code" "data" "Anal"
[1] "d" "t" "a"

Example 3: Replacing substrings in R using substring()

# R program to demonstrate
# substring replacement

# Initializing a character vector
vec <- c("Code", "data", "string")

# Replacing substrings
substring(vec, 2, 3) <- c("X")
print(vec)

Output:

[1] "CXde"  "dXta"  "sXring"

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *