Is there a fast way to convert latitude and longitude coordinates to State codes in R? I’ve been using the zipcode package as a look up table but it’s too slow when I’m querying lots of lat/long values
If not in R is there any way to do this using google geocoder or any other type of fast querying service?
Thanks!
Here are two options, one using sf and one using sp package functions. sf is the more modern (and, here in 2020, recommended) package for analyzing spatial data, but in case it’s still useful, I am leaving my original 2012 answer showing how to do this with sp-related functions.
Method 1 (using sf):
If you need higher resolution state boundaries, read in your own vector data as an
sfobject usingsf::st_read()or by some other means. One nice option is to install the rnaturalearth package and use it to load a state vector layer from rnaturalearthhires. Then use thelonlat_to_state()function we just defined as shown here:For very accurate results, you can download a geopackage containing GADM-maintained administrative borders for the United States from this page. Then, load the state boundary data and use them like this:
Method 2 (using sp):
Here is a function that takes a data.frame of lat-longs within the lower 48 states, and for each point, returns the state in which it is located.
Most of the function simply prepares the
SpatialPointsandSpatialPolygonsobjects needed by theover()function in thesppackage, which does the real heavy lifting of calculating the ‘intersection’ of points and polygons: