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:

StateScore
Kerala622
TN247
AP455
HYD174
GOA321

๐Ÿ”น 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:

StateScoreStateLeft
Kerala622######Kerala
TN247##########TN
AP455##########AP
HYD174#########HYD
GOA321#########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:

StateStateRight
KeralaKerala######
TNTN##########
APAP##########
HYDHYD#########
GOAGOA#########

๐Ÿ”ธ 3. Padding on Both Sides

For symmetric padding, use side = "both".

r

df$StateBoth <- str_pad(df$State, width = 12, side = "both", pad = "#")

๐ŸŽฏ Result:

StateStateBoth
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!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

8 + 10 =

Ads Blocker Image Powered by Code Help Pro

Quality articles need supporters. Will you be one?

You currently have an Ad Blocker on.

Please support FINNSTATS.COM by disabling these ads blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock