How to Remove Spaces from Strings in R (3 Examples)


You can use the following methods to remove white spaces from strings in R:

Method 1: Remove All Whitespaces Using gsub()

updated_string <- gsub(" ", "", my_string)

Method 2: Remove All Whitespaces Using str_replace_all()

library(stringr)

updated_string <- str_replace_all(my_string, " ", "")

Method 3: Remove Leading & Trailing Whitespaces Using str_trim()

library(stringr)

#remove all trailing whitespace
updated_string <- str_trim(my_string, "right")

#remove all leading whitespace
updated_string <- str_trim(my_string, "left")

The following examples show how to use each method in practice.

Example 1: Remove All Whitespaces Using gsub()

The following code shows how to use the gsub() function from base R to remove all whitespaces from a given string:

#create string
my_string <- "Check out this cool string"

#remove all whitespace from string
updated_string <- gsub(" ", "", my_string)

#view updated string
updated_string

[1] "Checkoutthiscoolstring"

Notice that all whitespaces have been removed from the string.

Example 2: Remove All Whitespaces Using str_replace_all()

The following code shows how to use the str_replace_all() function from the stringr package in R to remove all whitespaces from a given string:

library(stringr)

#create string
my_string <- "Check out this cool string"

#remove all whitespace from string
updated_string <- str_replace_all(my_string, " ", "")

#view updated string
updated_string

[1] "Checkoutthiscoolstring"

Notice that all whitespaces have been removed from the string.

Example 3: Remove Leading & Trailing Whitespaces Using str_trim()

The following code shows how to use the str_trim() function from the stringr package in R to remove all leading whitespace from a given string:

library(stringr)

#create string with leading whitespace
my_string <- "    Check out this cool string"

#remove all leading whitespace from string
updated_string <- str_trim(my_string, "left")

#view updated string
updated_string

[1] "Check out this cool string"

Notice that all of the leading whitespace has been removed.

The following code shows how to use the str_trim() function to remove all trailing whitespace from a given string:

library(stringr)

#create string with trailing whitespace
my_string <- "Check out this cool string    "

#remove all trailing whitespace from string
updated_string <- str_trim(my_string, "right")

#view updated string
updated_string

[1] "Check out this cool string"

Notice that all of the trailing whitespace has been removed.

Additional Resources

The following tutorials explain how to perform other common operations in R:

How to Find Location of Character in a String in R
How to Concatenate Strings in R
How to Convert a Vector to String in R
How to Convert Character to Factor in R

Leave a Reply

Your email address will not be published. Required fields are marked *