Alignment

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.

Left Align

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.
  • We use the str_pad() for alignment as follows:
    • We pass the column whose values we wish to align as the first argument; which here is col_1.
    • We pass the line width, which here is 25, as the second argument.
    • We pass the side we wish to add padding at as the third argument, which here is side = 'right' because we wish to left align (in left aligning, the empty space is on the right).
    • We do not pass any value to the pad parameter because the default is an empty space like we need.
  • Note: There is an StrAlign() function in the DescTools package though.

Right Align

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).

Center Align

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.

R
I/O