Splitting Strings in R programming – strsplit() method

strsplit() method in detail

The strsplit() function in R is used to divide a string into smaller parts based on a specified delimiter.

Syntax of strsplit()

strsplit(string, split, fixed)

Parameters:

  • string: The input text or vector of strings.
  • split: The character or pattern used to split the string.
  • fixed: A logical value indicating whether the split should be treated as a literal match (TRUE) or as a regular expression (FALSE).

Return Value:

It returns a list containing the substrings obtained after the split.

Examples of Splitting Strings in R

Example 1: Using strsplit() with a Space as a Delimiter

In this example, we use the strsplit() function to split a given text using space (" ") as a delimiter.

# R program to split a string

# Given String
text <- "Data Science with R"

# Using strsplit() method
result <- strsplit(text, " ")

print(result)

Output:

[[1]]
[1] "Data"    "Science" "with"    "R"

Example 2: Using Regular Expression to Split a String

Here, we use a regular expression to split the string wherever one or more numeric characters ([0-9]+) appear.

# R program to split a string using regex

# Given String
text <- "Learn7R5Programming"

# Using strsplit() method
result <- strsplit(text, split = "[0-9]+")

print(result)

Output:

[[1]]
[1] "Learn"      "R"          "Programming"

Example 3: Splitting Date Strings Using strsplit()

We can also split date strings into separate components using a specific delimiter, such as "-".

# R program to split date strings

# Given Date Strings
date_strings <- c("10-05-2023", "15-06-2023", "20-07-2023", "25-08-2023", "30-09-2023")

# Using strsplit() function
result <- strsplit(date_strings, split = "-")

print(result)

Output:

[[1]]
[1] "10"  "05"  "2023"

[[2]]
[1] "15"  "06"  "2023"

[[3]]
[1] "20"  "07"  "2023"

[[4]]
[1] "25"  "08"  "2023"

[[5]]
[1] "30"  "09"  "2023"

Comments

Leave a Reply

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