Set Multiple Split Arguments in strsplit Function in R (Example)

 

This article shows how to define several split conditions in the strsplit function in the R programming language.

The table of content looks as follows:

Sound good? Great, let’s get started…

 

Construction of Example Data

We’ll use the following data as basement for this R tutorial:

my_string <- "aaaxbbbycccxddd"    # Create example character string
my_string                         # Print example character string
# [1] "aaaxbbbycccxddd"

Have a look at the previously shown output of the RStudio console. It shows that our example data is a single character string containing different letters.

 

Example: Specify Multiple Conditions in strsplit() Function

In this example, I’ll explain how to divide a character string based on multiple splitting arguments within the strsplit function.

Let’s first see how the strsplit function works with only one split condition:

strsplit(my_string, "x")          # strsplit with one condition
# [[1]]
# [1] "aaa"     "bbbyccc" "ddd"

As you can see, the previous R code has split our character string at each position where the character x was stored in the input data object.

Now, let’s assume that we want to split our character string according to two different splitting conditions, i.e. x and y. Then, we can use the | operator as shown in the following R code:

strsplit(my_string, "x|y")        # strsplit with multiple conditions
# [[1]]
# [1] "aaa" "bbb" "ccc" "ddd"

The previous output shows that we have split our character string at each positions of x and y. Looks good!

 

Video, Further Resources & Summary

If you need more explanations on the R programming codes of this article, you may watch the following video on the Statistics Globe YouTube channel. I’m explaining the R programming codes of this article in the video instruction.

 

 

In addition, you may have a look at the related R tutorials on www.statisticsglobe.com. I have released numerous tutorials that are related to the usage of several split conditions in the strsplit function already:

 

In this R tutorial you have learned how to set multiple split conditions in the strsplit function. If you have additional questions, let me know in the comments.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Top