Split Character String at Whitespace in R (2 Examples)
In this R tutorial you’ll learn how to split character strings by spaces.
Table of contents:
Let’s just jump right in:
Introduction of Example Data
To start with, we’ll need to create some data that we can use in the examples later on:
my_string <- "aaa b cc ddd e" # Create example character string my_string # Print example character string # [1] "aaa b cc ddd e"
Have a look at the previous RStudio console output. It shows that our example data is a single character string object containing different alphabetical letters and numerous spaces.
Example 1: Split Character String at Whitespace Using strsplit() Function
Example 1 illustrates how to use the strsplit function to split our character string based on any number of spaces.
For this, we have to specify ” +” as a splitting condition:
my_string_split1 <- strsplit(my_string, " +")[[1]] # Apply strsplit function my_string_split1 # Print split character string vector # [1] "aaa" "b" "cc" "ddd" "e"
Have a look at the previous output of the RStudio console. As you can see, we have created a character vector where each vector element was defined by the whitespace in our input character string.
Example 2: Split Character String at Whitespace Using scan() Function
Example 2 demonstrates how to apply the scan function to divide our character string into chunks.
Within the scan function, we have to specify the text and what arguments:
my_string_split2 <- scan(text = my_string, what = "") # Apply scan function my_string_split2 # Print split character string vector # [1] "aaa" "b" "cc" "ddd" "e"
The previous output shows exactly the same character vector as in Example 1. Whether you prefer the strsplit or the scan function to divide your data based on spaces is a matter of taste.
Video, Further Resources & Summary
Have a look at the following video of my YouTube channel. In the video, I’m explaining the topics of this tutorial in a live session.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you might want to read some of the related tutorials on this website.
- strsplit Function in R
- Split Character String into Chunks in R
- Split Data Frame Variable into Multiple Columns
- Insert Character Pattern at Particular Position of String
- Introduction to R
In this R programming tutorial you have learned how to split a character string into a vector by any number of spaces. If you have further comments or questions, don’t hesitate to tell me about it in the comments section.
Statistics Globe Newsletter