stringr::str_trim

Function of the Week

Removes whitespace from the begining and/or end of a string
Author

Destine Krenik

Published

February 27, 2025

1 str_trim()

In this document, I will introduce the str_trim function and show what it’s for.

#load libraries
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.1     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.1
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(stringr)

1.1 What is it for?

The str_trim() function removes whitespace from the begining and/or end of a string. You can specify which end by setting “side” equal to “left”, “right”, or “both”.

#Create example data frame
id <- c(1:3)
name_animal <- c(" Jeff bear", "Anne penguin   ", "       Richard lion ")

df1 <- data.frame(id, name_animal)
df2 <- data.frame(id, name_animal)
df3 <- data.frame(id, name_animal)

print(df1)
  id          name_animal
1  1            Jeff bear
2  2      Anne penguin   
3  3        Richard lion 
#What happens if you try to separate the column name_animal?
df_sep <- df1 %>%
  separate(col = name_animal,
           into = c("name", "animal"),
           sep = " ")
Warning: Expected 2 pieces. Additional pieces discarded in 3 rows [1, 2, 3].
print(df_sep)
  id name  animal
1  1         Jeff
2  2 Anne penguin
3  3             
#Trim whitespace from the beginning
str_trim(df1$name_animal, side = "left")
[1] "Jeff bear"       "Anne penguin   " "Richard lion "  
#Trim whitespace from the end
str_trim(df2$name_animal, side = "right")
[1] " Jeff bear"          "Anne penguin"        "       Richard lion"
#Trim whitespace from both sides
str_trim(df3$name_animal, side = "both")
[1] "Jeff bear"    "Anne penguin" "Richard lion"
#Now what happens when we try to separate our cleaned vector?
df3 <- df3 %>%
  mutate(name_animal = str_trim(name_animal))

df_sep <- df3 %>%
  separate(col = name_animal,
           into = c("name", "animal"),
           sep = " ")

print(df_sep)
  id    name  animal
1  1    Jeff    bear
2  2    Anne penguin
3  3 Richard    lion

1.2 Is it helpful?

This function can be very helpful when cleaning data. However, there is another function that may be better for general use called str_squish(). The str_squish() function removes all excess whitespace from the beginning and end of a string, and replaces all whitespace between words with a single space.