Reputation: 1499
I have a df:
ZIP_CODE PO_NAME STATE ZCTA
1 501 Holtsville NY 11742
2 544 Holtsville NY 11742
3 601 Adjuntas PR 601
4 602 Aguada PR 602
5 1002 Boston MA 1002
6 90210 Los Angeles CA 90210
I would like to make to make the ZIP codes and the ZCTA column five digits by adding zeroes in front of the current values if they are 3 or 4 digits. For example, 501 would become 00501. How is this done?
Output:
ZIP_CODE PO_NAME STATE ZCTA
1 00501 Holtsville NY 11742
2 00544 Holtsville NY 11742
3 00601 Adjuntas PR 00601
4 00602 Aguada PR 00602
5 01002 Boston MA 01002
6 90210 Los Angeles CA 90210
Upvotes: 1
Views: 52
Reputation: 887108
We can use sprintf
(assuming the columns are numeric)
df1$ZIP_CODE <- sprintf("%05d", df1$ZIP_CODE)
df1$ZCTA <- sprintf("%05d", df1$ZCTA)
Or doing this in a single step
df1[c("ZIP_CODE", "ZCTA")] <- lapply(df1[c("ZIP_CODE", "ZCTA")],
sprintf, fmt = "%05d")
Or in tidyverse/stringr
library(dplyr)
library(stringr)
df1 %>%
mutate_at(vars(ZIP_CODE, ZCTA), str_pad, width = 5, pad = '0')
# ZIP_CODE PO_NAME STATE ZCTA
#1 00501 Holtsville NY 11742
#2 00544 Holtsville NY 11742
#3 00601 Adjuntas PR 00601
#4 00602 Aguada PR 00602
#5 01002 Boston MA 01002
#6 90210 Los Angeles CA 90210
df1 <- structure(list(ZIP_CODE = c(501L, 544L, 601L, 602L, 1002L, 90210L
), PO_NAME = c("Holtsville", "Holtsville", "Adjuntas", "Aguada",
"Boston", "Los Angeles"), STATE = c("NY", "NY", "PR", "PR", "MA",
"CA"), ZCTA = c(11742L, 11742L, 601L, 602L, 1002L, 90210L)),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
Upvotes: 4
Reputation: 6226
You can use stringr::str_pad
:
library(stringr)
df %>% mutate(ZIP_CODE = str_pad(ZIP_CODE, 5, pad = "0", side = "left"),
ZCTA = str_pad(ZCTA, 5, pad = "0", side = "left"))
Upvotes: 3