How to Split a Character String by Any Number of Spaces (Example Code)

This tutorial shows how to split a character string into a vector by any number of whitespaces in the R programming language.

Creation of Example Data

x <- "1  2 3      4 5    6 7"    # Create example character string
x                                # Print example character string
# [1] "1  2 3      4 5    6 7"

Example: Split Character String at Whitespace Using strsplit() Function

strsplit(x, "\s+")[[1]]         # Apply strsplit function
# [1] "1" "2" "3" "4" "5" "6" "7"

Related Articles & Further Resources

Have a look at the following R programming tutorials. They illustrate topics such as coding errors, data conversion, loops, and vectors:

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.
You need to agree with the terms to proceed