Get County and State using zip code (reverze_zipcode)

384 views Asked by At

I have a list of unique client names and their zip codes.

I need to get extra information regarding the zip code such as state and county.

I discovered the package zipcodeR but wasn't able to use the reverse_zipcode function.

Below is a sample dataset.

df <- data.frame(name = c('Juan', 'Alice', 'Tim', 'Joe'),
                 zipc = c('11374', '11374', '11379', 'A145'))

I need an state and county column for my dataframe.

   name  zipc
1  Juan 11374
2 Alice 11374
3   Tim 11379
4   Joe  A145
2

There are 2 answers

1
TarJae On BEST ANSWER

Using zipcodeR package it can be done as follows:

library(dplyr)
library(zipcodeR)

zip_code_db %>% 
  select(zipcode, state, county) %>% 
  right_join(df, by = c("zipcode"="zipc"), multiple = "all")

  zipcode state        county  name
1   11374    NY Queens County  Juan
2   11374    NY Queens County Alice
3   11379    NY Queens County   Tim
4    A145  <NA>          <NA>   Joe
2
Joe Robert On

It looks like the reverse_zipcode function doesn't return a value, even NA, when it can't find the zip code in the zip_code_db data frame included with the zipcodeR package. The example below checks whether the zip code "looks" correct and otherwise returns NA:

library(zipcodeR)
library(purrr)
library(dplyr)
data.frame(name = c('Juan', 'Alice', 'Tim', 'Joe'),
                 zipc = c('11374', '11374', '11379', 'A145')) %>%
  mutate(test2 = map_chr(zipc,
                         ~ ifelse(str_length(.) == 5 & !is.na(as.numeric(.)),
                                  zipcodeR::reverse_zipcode(.)$state,NA)))