Home » How to Use strsplit() Function in R to Split Elements of String

How to Use strsplit() Function in R to Split Elements of String

by Erma Khan

The strsplit() function in R can be used to split a string into multiple pieces. This function uses the following syntax:

strsplit(string, pattern)

where:

  • string: Character vector
  • pattern: Pattern to split on

The following examples show how to use this function in practice.

Example 1: Split String Based on Spaces

The following code shows how to use the strsplit() function to split a string based on spaces:

#split string based on spaces
split_up Hey there people", split=" ")

#view results
split_up

[[1]]
[1] "Hey"    "there"  "people"

#view class of split_up
class(split_up)

[1] "list"

The result is a list of three elements that are split based on the spaces in the original string.

We can use the unlist() function if we would instead like to produce a vector as the result:

#split string based on spaces
split_up Hey there people", split=" "))

#view results
split_up

[1] "Hey"    "there"  "people"

#view class of split_up
class(split_up)

[1] "character"

We can see that the result is a character vector.

Example 2: Split String Based on Custom Delimiter

We can also use the strplit() function to split a string based on a custom delimiter, such as a dash:

#split string based on dashes
strsplit("Hey-there-people", split="-")

[[1]]
[1] "Hey"    "there"  "people"

The result is a list of three elements that are split based on the dashes in the original string.

Example 3: Split String Based on Several Delimiters

We can also use brackets within the split argument of the strplit() function to split a string based on several different delimiters:

#split string based on several delimiters
strsplit("Hey&there-you/people", split="[&-/]")

[[1]]
[1] "Hey"    "there"  "you"    "people"

The result is a list of elements that were split whenever any of the following delimiters were present in the original string:

  • Ampersand (&)
  • Dash ()
  • Slash (/)

Additional Resources

The following tutorials explain how to perform other common operations with strings in R:

How to Use str_replace in R
How to Perform Partial String Matching in R
How to Convert Strings to Dates in R
How to Convert Character to Numeric in R

Related Posts