0
0
R-programmingHow-ToBeginner ยท 3 min read

How to Use str_trim in R to Remove Whitespace

In R, use str_trim() from the stringr package to remove spaces at the start and end of a string. It cleans up text by trimming whitespace, making your data neater and easier to work with.
๐Ÿ“

Syntax

The basic syntax of str_trim() is:

  • str_trim(string, side = "both")

Here, string is the text you want to trim.

side controls which side to trim: "both" (default), "left", or "right".

r
str_trim(string, side = "both")
๐Ÿ’ป

Example

This example shows how to remove spaces from the start and end of strings using str_trim(). It also shows trimming only the left or right side.

r
library(stringr)

text <- c("  hello  ", "  world", "test  ")

trim_both <- str_trim(text)
trim_left <- str_trim(text, side = "left")
trim_right <- str_trim(text, side = "right")

trim_both
trim_left
trim_right
Output
[1] "hello" "world" "test" [1] "hello " "world" "test " [1] " hello" " world" "test"
โš ๏ธ

Common Pitfalls

One common mistake is forgetting to load the stringr package before using str_trim(). Another is expecting it to remove spaces inside the string, but it only trims spaces at the start and end.

Also, using base R's trimws() is an alternative but has slightly different options.

r
text <- "  example text  "

# Wrong: using str_trim without loading stringr
# str_trim(text)  # Error: could not find function "str_trim"

# Correct:
library(stringr)
str_trim(text)

# Note: str_trim only trims edges, not spaces inside
str_trim("  a b c  ")  # returns "a b c"
Output
[1] "example text" [1] "a b c"
๐Ÿ“Š

Quick Reference

ParameterDescriptionDefault
stringThe text to trim whitespace fromRequired
sideWhich side to trim: "both", "left", or "right""both"
โœ…

Key Takeaways

Use str_trim() from stringr to remove spaces at the start and end of strings.
Load the stringr package with library(stringr) before using str_trim().
The side parameter controls trimming direction: both, left, or right.
str_trim() does not remove spaces inside the string, only at edges.
For base R, trimws() is a similar alternative but with different options.