How to Use str_trim in R (With Examples)


The str_trim() function from the stringr package in R can be used to trim whitespace from a string.

This function uses the following syntax:

str_trim(string, side = c(“both”, “left”, “right”))

where:

  • string: Character vector
  • pattern: Side on which to remove whitespace

The following examples show how to use this function in practice

Example 1: Trim Whitespace from Left Side

The following code shows how to use the str_trim() function to trim whitespace from the left side of a string:

library(stringr)

#create string
my_string <- "   Hey there everyone.  "

#view string
my_string

[1] "   Hey there everyone.  "

#create new string with white space removed from left
new_string <- str_trim(my_string, side="left")

#view new string
new_string

[1] "Hey there everyone.  "

Notice that all of the whitespace on the left side of the string has been trimmed.

Example 2: Trim Whitespace from Right Side

The following code shows how to use the str_trim() function to trim whitespace from the right side of a string:

library(stringr)

#create string
my_string <- "   Hey there everyone.  "

#view string
my_string

[1] "   Hey there everyone.  "

#create new string with white space removed from right
new_string <- str_trim(my_string, side="right")

#view new string
new_string

[1] "   Hey there everyone."

Notice that all of the whitespace on the right side of the string has been trimmed.

Example 3: Trim Whitespace from Both Sides

The following code shows how to use the str_trim() function to trim whitespace from both sides of a string:

library(stringr)

#create string
my_string <- "   Hey there everyone.  "

#view string
my_string

[1] "   Hey there everyone.  "

#create new string with white space removed from both sides
new_string <- str_trim(my_string, side="both")

#view new string
new_string

[1] "Hey there everyone."

Notice that all of the whitespace on both sides of the string have been trimmed.

Additional Resources

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

How to Use str_replace in R
How to Use str_split in R
How to Use str_detect in R
How to Use str_count in R

Leave a Reply

Your email address will not be published.