Skip to content

Instantly share code, notes, and snippets.

@Radcliffe
Created February 20, 2016 06:46
Show Gist options
  • Save Radcliffe/affc1eaa5e84ff880516 to your computer and use it in GitHub Desktop.
Save Radcliffe/affc1eaa5e84ff880516 to your computer and use it in GitHub Desktop.
Zip codes and congressional disricts -- R script
# This R script generates a correspondence between ZIP codes and
# US Congressional Districts (113th Congress)
# by merging two data files from the US Census Bureau website.
#
# Note that the relation is many-to-many, since a ZIP code can cross
# several districts, and a district can cross several ZIP codes.
library(data.table)
district_zip <- fread(
'http://www2.census.gov/geo/relfiles/cdsld13/natl/natl_zccd_delim.txt',
skip = 1, colClasses = 'c')
state_codes <- fread(
'http://www2.census.gov/geo/docs/reference/state.txt',
sep='|', colClasses = 'c')
district_zip <- merge(district_zip, state_codes, by.x='State', by.y='STATE')
colnames(district_zip) <- c('State', 'ZipCode', 'CongressionalDistrict',
'StateAbbrev', 'StateName', 'STATENS')
write.csv(district_zip, 'zipcode-to-congressional-district.csv', row.names=F)
@jlev
Copy link

jlev commented Mar 18, 2017

Hey, I found this script while looking for an updated mapping of zip codes to Congressional Districts for the 115th congress. There was redistricting in Florida, Minnesota, North Carolina and Virginia in 2016, which is included in http://www2.census.gov/geo/relfiles/cdsld16/natl/natl_zccd_delim.txt

However, that file doesn't include ZCTAs for any states that have at-large districts (AK,DE,MT,ND,SD,VT,WY,PR,DC), or the US Minor Outlying Islands. It also has a few nasty errors, including a bunch of null values and districts in CO that seem incorrect.

I wrote a python script to munge all that together, and put it at https://github.com/spacedogXYZ/us_zipcodes_congress, in case you're looking for an update. I've spot checked it for sanity, and I think it's the best open source of this data around. Feel free to open an issue if you see any errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment