We wish to align text to the left, right, or center within a given width specified as a number of characters.
Note that if the length of the string is larger than the specified line width, the original string is returned as is.
We wish to align text to the left of each line with empty spaces added to the right to fill the desired width of the line.
In this example, we wish to align the values of the string column col_1
to the left while setting the line width to 25.
df_2 = df %>%
mutate(col_2 = str_pad(col_1, 25, side = 'right'))
Here is how this works:
Stringr
doesn't offer an explicit align function, therefore we realize alignment via padding with the str_pad()
function. See Padding.str_pad()
for alignment as follows:col_1
.side = 'right'
because we wish to left align (in left aligning, the empty space is on the right).pad
parameter because the default is an empty space like we need.StrAlign()
function in the DescTools
package though.We wish to align text to the right of each line with empty spaces added to the left to fill the desired width of the line.
In this example, we wish to align the values of the string column col_1
to the right while setting the line width to 25.
df_2 = df %>%
mutate(col_2 = str_pad(col_1, 25, side = 'left'))
Here is how this works:
This works similarly to the Left Align case above except that we add padding to the left, hence side = ‘left’
, because we wish to align right (in right aligning, the empty space is on the left).
We wish to align text to the center of each line with empty spaces added to the left and the right to fill the desired width of the line.
In this example, we wish to align the values of the string column col_1
to the center while setting the line width to 25.
df_2 = df %>%
mutate(col_2 = str_pad(col_1, 25, side = 'both'))
Here is how this works:
This works similarly to the Left Align case above except that we add padding to both the left and the right, hence side = ‘both’
, because we wish to center right.