zero padding to numbers in column str_pad rlang – Code Example

Total
0
Shares

In this article we will look at the code example in Rlang to zero pad or prefix the numbers in columns using str_pad. Padding a number is useful to have similar formatting in a list of numbers where length of digits are different. So, a list of 1 to 100 numbers will look good if it starts with 001 to 100.

Code Example –

Suppose you have a table –

Code      Name         alias
10       Tony Stark    Ironman
11       Steve Rogers  Captain America
12       Bruce Banner  Hulk
13       Peter Parker  Spiderman

Now, if you want to add 0 padding to the code field, you can use this –

library(tidyverse)

df <- read.table(text = "Code      Name         alias
10       Tony Stark    Ironman
11       Steve Rogers  Captain America
12       Bruce Banner  Hulk
13       Peter Parker  Spidermana", header = T)

df %>% 
  mutate(Code = str_pad(Code, width = 3, pad = "0"))

The output will be –

Code      Name          alias
010       Tony Stark    Ironman
011       Steve Rogers  Captain America
012       Bruce Banner  Hulk
013       Peter Parker  Spidermana

Method 2: Using sprintf

df1$Code <- sprintf("%03d", df1$Code)

Method 3: Using formatC

df$Code <- formatC(df$Code, width = 3, format = "d", flag = "0")