rguides

stringr::str_pad()

str_pad(string, width, side = c("left", "right", "both"), pad = " ")

The str_pad() function from stringr pads a string to a specified width by adding filler characters. It is useful for aligning text, creating fixed-width output, and formatting data for display or export.

Syntax

str_pad(string, width, side = c("left", "right", "both"), pad = " ")

Parameters

ParameterTypeDefaultDescription
stringcharacterRequiredA character vector to pad
widthnumericRequiredMinimum width of the resulting string
sidecharacter”left”Which side to pad: “left”, “right”, or “both”
padcharacter” “Character to use for padding

Examples

The examples below show how str_pad() handles different padding scenarios, from basic left alignment to formatting numeric identifiers with leading zeros.

Basic usage

library(stringr)

# Pad strings to width 10 on the left (default)
str_pad(c("apple", "banana", "cherry"), width = 10)
# [1] "     apple" "    banana" "   cherry"

By default, str_pad() adds spaces to the left side of each string, which right-aligns the text content within the specified width. This is useful for formatting columns of varying-length strings so that they line up neatly when printed in the console or a report.

Pad on the right

# Pad on the right side
str_pad(c("apple", "banana", "cherry"), width = 10, side = "right")
# [1] "apple     " "banana    " "cherry    "

Setting side = "right" adds spaces after each string, resulting in left-aligned text within the fixed width. This approach is common when you want labels or names to start at the same column position without trailing space affecting visual alignment.

Pad on both sides

# Center the string by padding both sides
str_pad(c("apple", "banana"), width = 10, side = "both")
# [1] "  apple   " "  banana  "

The side = "both" option distributes padding evenly on both sides of the string, which effectively centres the text within the target width. When the extra space cannot be split evenly, the extra character goes to the left side first.

Use a custom padding character

# Pad with zeros
str_pad("123", width = 6, pad = "0")
# [1] "000123"

# Pad with dashes
str_pad("test", width = 8, pad = "-")
# [1] "----test"

You can replace the default space padding with any single character using the pad argument. Zero-padding is especially common for standardising numeric identifiers, while other characters like dashes or underscores are useful for creating visual separators in formatted output.

Working with numeric values

# Format numbers with leading zeros
nums <- c(1, 23, 456, 7890)
str_pad(nums, width = 5, pad = "0")
# [1] "00001" "00023" "00456" "78900"

When you pass numeric vectors to str_pad(), the function automatically converts them to character strings before padding. This makes it easy to format numbers as fixed-width character fields, which is essential for generating identifiers with leading zeros or preparing data for systems that expect fixed-width text input.

Combining with other stringr functions

# Trim and then pad to ensure consistent width
strings <- c("  hello  ", "world", "  test  ")
str_pad(str_trim(strings), width = 10)
# [1] "     hello" "     world" "      test"

Chaining str_trim() with str_pad() produces clean, consistently sized output by first removing any stray whitespace and then padding the strings to the desired width. This pairing is common when you are cleaning raw text data that may contain irregular spacing before formatting it for display.

Common use cases

  • Data alignment: Create aligned table output
  • Fixed-width format: Prepare data for fixed-width file formats
  • Number formatting: Add leading zeros to identifiers or numbers
  • Text justification: Left, right, or center text alignment

In data reporting workflows, padding is often the final step before presenting results. After computing values, you can apply str_pad() to align columns so that output looks professional and is easy to scan.

Creating a formatted table

library(dplyr)

df <- data.frame(
  name = c("Alice", "Bob", "Charlie"),
  score = c(95, 87, 100)
)

df %>%
  mutate(
    name = str_pad(name, width = 10, side = "right"),
    score = str_pad(as.character(score), width = 3, pad = "0", side = "left")
  )
#      name   score
# 1 Alice     095
# 2 Bob       087
# 3 Charlie   100

Combining str_pad() with dplyr::mutate() lets you format multiple columns in a single pipeline, which keeps your data preparation code concise and readable. Each column receives its own padding specification for width, side, and fill character, giving you fine-grained control over how the final output is presented.

Preparing for fixed-width files

# Ensure each field has a fixed width for fixed-width format
data <- data.frame(
  id = str_pad(1:3, width = 5, pad = "0"),
  value = str_pad(c("A", "BB", "CCC"), width = 5, pad = " ")
)

paste0(data$id, data$value)
# [1] "00001    A" "00002   BB" "00003  CCC"

stringr::str_pad() in practice

str_pad() extends strings to a minimum width by adding padding characters. The side argument controls where padding is added: "left" (right-align), "right" (left-align, default), or "both" (center). The pad argument specifies the fill character (default: space).

str_pad(c("1","23","456"), width=4) gives c(" 1"," 23"," 456") with left padding, each string is padded on the left to reach width 4. This is the standard way to right-align numbers in text output. str_pad(x, width=4, pad="0") gives zero-padded numbers: c("0001","0023","0456"), useful for generating fixed-width identifiers.

str_pad() does not truncate strings that are already longer than width. Strings that exceed the target width are returned unchanged. To both pad and truncate, use str_pad() followed by str_trunc().

format() from base R is an alternative for numeric formatting with padding, providing additional controls like scientific, big.mark, and decimal.mark. Use str_pad() for character padding of strings; use format() or sprintf() for formatted number display.

str_pad() vectorizes over string, width, and pad. When width is a vector, each element is padded to its corresponding target width, allowing variable-width padding across different elements.

See also