Add zero padding to numbers in a column by using str_pad in string package in r

Viewed 19

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 %>%?

0 Answers
Related