str_trim

The function stringr::str_trim() removes white spaces.

White spaces are:

  • Space:
  • Tab: \t
  • Newline: \n

Tidyverse reference page

String vector

Prior to using the function create a vector with various different strings.

#Create vector of strings
vec <- c("   Spaces to the left of me", 
        "Newlines to the right\n\n",
        "Here I am,", 
        "\t\tStuck in the middle of tabs\t\t")
#View vector
vec |> stringr::str_view()
[1] │    Spaces to the left of me
[2] │ Newlines to the right
    │ 
    │ 
[3] │ Here I am,
[4] │ {\t\t}Stuck in the middle of tabs{\t\t}

Default trimming

By default the command removes all white spaces from both sides of strings.

#Trim all white spaces from the start and end of strings
vec |> stringr::str_trim() |> stringr::str_view()
[1] │ Spaces to the left of me
[2] │ Newlines to the right
[3] │ Here I am,
[4] │ Stuck in the middle of tabs

Note:__str_trim() does not remove white spaces that are not at the start or end of a string.

"Here is a space: . Here is a tab:\t. Here is a new line:\n. " |>
    stringr::str_trim() |>
    stringr::str_view()
[1] │ Here is a space: . Here is a tab:{\t}. Here is a new line:
    │ .

Side

The side to remove white spaces from can be chosen with side=.

#Trim all white spaces from the start/left-side strings
vec |> stringr::str_trim(side = "left") |> stringr::str_view()
[1] │ Spaces to the left of me
[2] │ Newlines to the right
    │ 
    │ 
[3] │ Here I am,
[4] │ Stuck in the middle of tabs{\t\t}
#Trim all white spaces from the end/right-side strings
vec |> stringr::str_trim(side = "right") |> stringr::str_view()
[1] │    Spaces to the left of me
[2] │ Newlines to the right
[3] │ Here I am,
[4] │ {\t\t}Stuck in the middle of tabs
#Trim all white spaces from  bothsides strings
vec |> stringr::str_trim(side = "both") |> stringr::str_view()
[1] │ Spaces to the left of me
[2] │ Newlines to the right
[3] │ Here I am,
[4] │ Stuck in the middle of tabs