How to make a colmn in a dataframe have a given number of digits

I need some of the variables of my dataframe to have a given number of digits. In this case, I need "st" variable to have 2 digits and "county" variable to have 3 digits.

Let's say I have this dataframe:

state(Alabama, Alabama, Alabama, Alabama, Alabama, Alabama)
st(3,5,7,9,11,13)
county(7, 33, 15, 17, 111, 189)
state_county <- data.frame(state, st, county)

And I want to get this:

tate(Alabama, Alabama, Alabama, Alabama, Alabama, Alabama)
st(03,05,07,09,11,13)
county(007, 033, 015, 017, 111, 189)
state_county1 <- data.frame(state, st, county)

Thanks!

You can do this if you don't mind that the columns st and county become characters.

state <- c("Alabama", "Alabama", "Alabama", "Alabama", "Alabama", "Alabama")
st <- c(3,5,7,9,11,13)
county <- c(7, 33, 15, 17, 111, 189)
state_county <- data.frame(state, st, county)
state_county <- state_county |> 
   mutate(st = formatC(st, width = 2, flag = "0"),
          county = formatC(county, width = 3, flag = "0"))
state_county
    state st county
1 Alabama 03    007
2 Alabama 05    033
3 Alabama 07    015
4 Alabama 09    017
5 Alabama 11    111
6 Alabama 13    189

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.