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 first step, we’ll have to create some example data:

x <- "  AAA BBB     CCC DDD "            # Create example string
x                                        # Print example string
# [1] "  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
# [1] "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
# [1] "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.

 

The YouTube video will be added soon.

 

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.

 

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.

 

Subscribe to my free statistics 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.

Menu
Top