str_split & str_split_fixed Functions in R (2 Examples)


This post illustrates how to use str_split and str_split_fixed to split up a string into pieces in the R programming language.

Table of contents:

Here’s how to do it!


Creation of Exemplifying Data

In the examples of this R tutorial, I’ll use the following character string.

x <- c("hey, look at my string")         # Create vector of character strings

In order to use the str_split and str_split_fixed commands of the stringr add-on package, we also need to install and load the package to R:

install.packages("stringr")              # Install stringr package
library("stringr")                       # Load stringr package

Keep on reading, we are now moving on to the examples…


Example 1: Application of str_split Function in R

This example shows how to apply the str_split function in R. Let’s have a look at the following R code:

str_split(x, "at")                       # Apply str_split function
# [[1]]
# [1] "hey, look " " my string"

As you can see based on the previous output of the RStudio console, the str_split function returned a list with one list element. This list element contains a vector of two character strings split before and after the patter “at”.


Example 2: Application of str_split_fixed Function in R

Sometime we might prefer to have a fixed length of our new vector of character strings that we retain after splitting our character string. In this case we can use the str_split_fixed command and specify a certain length:

str_split_fixed(x, "at", 5)              # Apply str_split_fixed function
#      [,1]         [,2]         [,3] [,4] [,5]
# [1,] "hey, look " " my string" ""   ""   ""

The str_split_fixed function returns a matrix with our specified length (i.e. the number of columns is five). Each cell of the matrix, which is longer than our input character string, is filled with empty quotation marks.

The advantage of this method is that we can easily combine multiple strings into a matrix or a data frame.


Video, Further Resources & Summary

In case you need further information on the R programming codes of this article, I can recommend to watch the following video of my YouTube channel. In the video, I show the R code of this post:


The YouTube video will be added soon.


Furthermore, you might read the related articles of this homepage.


At this point you should know how to divide a character string into pieces in the R programming language. If you have any additional questions, don’t hesitate to 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.