Home > Enterprise >  Add zero padding to numbers in a column by using str_pad in string package
Add zero padding to numbers in a column by using str_pad in string package

Time:07-24

I want to use the string str_pad function to make a column in my desired format, which includes zero padding the numbers in the "Code" column to 3 digits.

I've run this code:

Animals %>%
gather(most_common, cnt, M:OG) %>% 
group_by(name) %>% 
slice(which.max(cnt)) %>%
arrange(code)

Which resulted in the following tibble:

Code      Name       most_common
32       Monkey        Africa
33       Wolf          Europe
34       Tiger         Asia
35       Godzilla      Asia
#With 1 234 more rows

I'm happy with my code above. However, because I'm going to merge this df later on, I need the "Code" column to be three digits with zero padding (i.e. in the format "nnn" / "032"), as this:

Code      Name       most_common
032       Monkey        Africa
033       Wolf          Europe
034       Tiger         Asia
035       Godzilla      Asia
#With 1 234 more rows

I've run string str_pad($code, $3, $0), but it doesn't work. I guess there's something wrong there. Should I run this code wherever I want in my chunk or by using %>%?

CodePudding user response:

A possible solution:

library(tidyverse)

df <- read.table(text = "Code      Name       most_common
32       Monkey        Africa
33       Wolf          Europe
34       Tiger         Asia
35       Godzilla      Asia", header = T)

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

#>   Code     Name most_common
#> 1  032   Monkey      Africa
#> 2  033     Wolf      Europe
#> 3  034    Tiger        Asia
#> 4  035 Godzilla        Asia

CodePudding user response:

In base R, we can use sprintf

df1$Code <- sprintf("d", df1$Code)
  • Related