str_pad

The function stringr::str_pads() adds white space to strings to ensure it is a minimum length.

Tidyverse reference page

String vector

Prior to using the function create a vector with strings of length 1, 2, 4, and 8.

#Create vector of strings
vec <- c("1", "to", "four", "_eight_")
#View vector
vec |> stringr::str_view()
[1] │ 1
[2] │ to
[3] │ four
[4] │ _eight_

Default padding

Padding will add space to each string shorter than the specified pad length. These strings will have a total length (i.e. number of characters) equal to the pad length.

By default spaces () will be added to the start/left-side of the string for padding.

#Pad strings to a min length of 10
vec |> stringr::str_pad(10) |> stringr::str_view()
[1] │          1
[2] │         to
[3] │       four
[4] │    _eight_

Strings with a length equal to or greater than the pad length will be untouched.

#Pad strings to a min length of 4
vec |> stringr::str_pad(4) |> stringr::str_view()
[1] │    1
[2] │   to
[3] │ four
[4] │ _eight_

Side

The side to add the padding characters can be specified.

#Pad to the left, the default
vec |> stringr::str_pad(10, side = "left") |> stringr::str_view()
[1] │          1
[2] │         to
[3] │       four
[4] │    _eight_
#Pad to the right
vec |> stringr::str_pad(10, side = "right") |> stringr::str_view()
[1] │ 1         
[2] │ to        
[3] │ four      
[4] │ _eight_   
#Padd on both sides
vec |> stringr::str_pad(10, side = "both") |> stringr::str_view()
[1] │     1     
[2] │     to    
[3] │    four   
[4] │  _eight_  

Pad character

The padding character can be specified. This character can only have a length of one (i.e. “ or”||” cannot be used).

#Use pad character |
vec |> stringr::str_pad(10, pad = "|") |> stringr::str_view()
[1] │ |||||||||1
[2] │ ||||||||to
[3] │ ||||||four
[4] │ |||_eight_
#Use pad character .
vec |> stringr::str_pad(10, pad = ".") |> stringr::str_view()
[1] │ .........1
[2] │ ........to
[3] │ ......four
[4] │ ..._eight_
#Use pad character _ with padding on both sides
vec |> stringr::str_pad(10, pad = "_", side = "both") |> stringr::str_view()
[1] │ ____1_____
[2] │ ____to____
[3] │ ___four___
[4] │ __eight___