String pad to the column in R
Need to format your character columns for cleaner output or reporting?
In R, string padding allows you to add characters like "#"
to the left, right, or both sides of a string.
Whether it’s for aligning data or prepping CSV exports, str_pad()
from the stringr
package makes it easy.
In this tutorial, we’ll walk through three ways to pad strings in R using a practical example.
๐งช Step 1: Create Sample Data in R
r
df <- data.frame(
State = c('Kerala', 'TN', 'AP', 'HYD', 'GOA'),
Score = c(622, 247, 455, 174, 321)
)
df
โ Output:
State | Score |
---|---|
Kerala | 622 |
TN | 247 |
AP | 455 |
HYD | 174 |
GOA | 321 |
๐น 1. String Padding to the Left
Use str_pad()
with the default side = "left"
to pad characters to the left of each string.
r
library(stringr)
df$StateLeft <- str_pad(df$State, width = 12, pad = "#")
๐ฏ Result:
State | Score | StateLeft |
---|---|---|
Kerala | 622 | ######Kerala |
TN | 247 | ##########TN |
AP | 455 | ##########AP |
HYD | 174 | #########HYD |
GOA | 321 | #########GOA |
๐ธ 2. String Padding to the Right
To pad characters on the right, set side = "right"
.
r
df$StateRight <- str_pad(df$State, width = 12, side = "right", pad = "#")
๐ฏ Result:
State | StateRight |
---|---|
Kerala | Kerala###### |
TN | TN########## |
AP | AP########## |
HYD | HYD######### |
GOA | GOA######### |
๐ธ 3. Padding on Both Sides
For symmetric padding, use side = "both"
.
r
df$StateBoth <- str_pad(df$State, width = 12, side = "both", pad = "#")
๐ฏ Result:
State | StateBoth |
---|---|
Kerala | ###Kerala### |
TN | #####TN##### |
AP | #####AP##### |
HYD | ####HYD##### |
GOA | ####GOA##### |
๐ง Why String Padding Matters
- Align outputs in reports and dashboards
- Format export files and logs
- Add structure to categorical data
โ Conclusion
The str_pad()
function in R is a versatile tool for formatting string columns. Whether you need left, right, or full-width padding, stringr
provides a simple and consistent solution.
Explore more R tips at Finnstats and master your data one line of code at a time!