Home » How to Use str_pad in R (With Examples)

How to Use str_pad in R (With Examples)

by Erma Khan

The str_pad() function from the stringr package in R can be used to pad characters to a string.

This function uses the following syntax:

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

where:

  • string: Character vector
  • width: Minimum width of padded strings
  • side: Side to add padding character (Default is left)
  • pad: Character to use for padding (Default is space)

The following examples show how to use this function in practice

Example 1: Pad String with Spaces

The following code shows how to use the str_pad() function to pad the left side of a string with spaces until the string has 10 total characters:

library(stringr)

#create string
my_string 
#pad string to length of 10
str_pad(my_string, width=10)

[1] "     Rhino"

Notice that five spaces have been added to the left side of the string so that the string has a total length of 10.

Use the side argument to instead pad the right side of the string:

library(stringr)

#create string
my_string 
#pad string to length of 10
str_pad(my_string, width=10, side="right")

[1] "Rhino     "

Example 2: Pad String with Specific Character

The following code shows how to use the str_pad() function to pad the left side of a string with underscores until the string has 10 total characters:

library(stringr)

#create string
my_string 
#pad string to length of 10 using underscores
str_pad(my_string, width=10, pad="_")

[1] "_____Rhino"

Notice that five underscores have been added to the left side of the string so that the string has a total length of 10.

Example 3: Pad String with Specific Number of Characters

The following code shows how to use the str_pad() function along with the nchar() function to pad the left side of a string with a specific number (5) of characters:

library(stringr)

#create string
my_string 
#pad string with 5 A's
str_pad(my_string, width=nchar(my_string)+5, pad="A")

[1] "AAAAARhino"

Notice that five A’s have been padded to the left side of the string.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Use str_replace in R
How to Use str_split in R
How to Use str_detect in R
How to Use str_count in R

Related Posts