Remove All White Space from Character String in R (2 Examples)
In this R post you’ll learn how to delete white space from a character string.
Table of contents:
Let’s take a look at some R codes in action…
Creation of Exemplifying Data
As a first step, we’ll have to create some example data:
x <- " AAA BBB CCC DDD " # Create example string x # Print example string #  " AAA BBB CCC DDD "
The previous output of the RStudio console shows that the example data is a character string with multiple blanks stored in the data object x.
Example 1: Remove All White Space from Character String Using gsub() Function
This Example explains how to remove blanks from characters using the gsub function in R. Have a look at the following R code and its output:
x_new1 <- gsub(" ", "", x) # Applying gsub function x_new1 # Printing output to console #  "AAABBBCCCDDD"
As you can see, we have created a new data object called x_new1 that contains the same characters as the input data x, but without white space.
Example 2: Remove All White Space Using str_replace_all() Function of stringr Package
In Example 2, I’ll illustrate how to the stringr package to remove blanks from character strings.
If we want to use the functions of the stringr package, we first have to install and load stringr:
install.packages("stringr") # Install & load stringr library("stringr")
Now, we can apply the str_replace_all function of the stringr package as shown below:
x_new2 <- str_replace_all(x, " ", "") # Applying str_replace_all function x_new2 # Printing output to console #  "AAABBBCCCDDD"
The output is exactly the same as in Example 1.
Video & Further Resources
Would you like to know more about character strings in R? Then you could watch the following video of my YouTube channel. In the video, I show the content of this post in RStudio.
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.
Also, you may read the related tutorials of this website. I have published several other tutorials about similar topics such as data conversion, variables, and character strings.
- Convert All Character String Variables in Data Frame to Uppercase
- Remove All Special Characters from String in R
- The R Programming Language
You learned in this article how to extract blanks in characters in the R programming language. In case you have any additional questions, let me know in the comments section below.
Statistics Globe Newsletter