0

This is my first-ever posting.

I have Census Tract FIPS Codes that are 11-digit character strings. The Census Bureau CSV files have a column but some codes are only 9 or 10 digits. All observations of the code needs to be 11 characters. I have 77,000+ rows. Here is a slice of 10 rows.

DATA

b1 <- structure(list(geocode1 = c("9001990000", "9007990100", "9009990000", 
"9011990100", "23005990000", "23009990000", "23013990000", "23015990000", 
"23023990000", "23029990000")), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

CODE

str_pad(b1, 11, pad = "0")

ERROR

 str_pad(b1, 11, pad = "0")
[1] "c(\"9001990000\", \"9007990100\", \"9009990000\", \"9011990100\", \"23005990000\", \"23009990000\", \"23013990000\", \"23015990000\", \"23023990000\", \"23029990000\")"
Warning message:
In stri_pad_left(string, width, pad = pad, use_length = !use_width) :
  argument is not an atomic vector; coercing

COMMENTS I tried permutations of all arguments of stringr::str_pad. I also referred to the vignettes. The vignette examples work fine, but my own code does not. I created another example that works fine:

  a1 <- c(1, 2, 31, 201, 1006)
  a2 <- as.character(a1)
  a2
  str_pad(a2, 7, pad = "0")
  > str_pad(a2, 7, pad = "0")
 [1] "0000001" "0000002" "0000031" "0000201" "0001006"

QUESTION How do I get all observations in the FIPS Code character vector to be 11 characters by adding leading zeroes on the left?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 3
    `str_pad(b1$geocode1, 11, pad = "0")`. The function should be applied to a vector or a single column of a data frame, not the data frame itself (even if it only has one column). – Jon Spring Jul 20 '23 at 18:03
  • I was using the function in a pipe. It didn't work. However, when I used your single line of code, it worked on the vector. How would I use your solution in a pipe? Thanks, @JonSpring – RinconArtist Jul 20 '23 at 18:42
  • 1
    E.g. `b1 |> mutate(geocode1 = str_pad(geocode1, 11, pad = "0"))`. – Jan Jul 20 '23 at 19:02
  • Welcome to StackOverflow! Your problem was around how to apply a function to a specific column of a data.frame, not the stated question in the title which is answered in the duplicate-linked answer. The comments here show two ways to use `str_pad` on a column in a data.frame, so hopefully you're set. – Sam Firke Jul 20 '23 at 19:30
  • I just needed the "geocode1 = str_pad..." Thank you! – RinconArtist Jul 20 '23 at 19:30
  • 1
    @SamFirke, your statement is right. I'm a novice at R and coding. I'm all set. – RinconArtist Jul 20 '23 at 19:33

0 Answers0