Created
February 6, 2013 06:40
-
-
Save rweald/4720788 to your computer and use it in GitHub Desktop.
Convert (long,lat) pairs into state names
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Code taken from SO | |
#http://stackoverflow.com/questions/8751497/latitude-longitude-coordinates-to-state-code-in-r/8751965#8751965 | |
library(sp) | |
library(maps) | |
library(maptools) | |
# The single argument to this function, pointsDF, is a data.frame in which: | |
# - column 1 contains the longitude in degrees (negative in the US) | |
# - column 2 contains the latitude in degrees | |
latlong2state <- function(pointsDF) { | |
# Prepare SpatialPolygons object with one SpatialPolygon | |
# per state (plus DC, minus HI & AK) | |
states <- map('state', fill=TRUE, col="transparent", plot=FALSE) | |
IDs <- sapply(strsplit(states$names, ":"), function(x) x[1]) | |
states_sp <- map2SpatialPolygons(states, IDs=IDs, | |
proj4string=CRS("+proj=longlat +datum=wgs84")) | |
# Convert pointsDF to a SpatialPoints object | |
pointsSP <- SpatialPoints(pointsDF, | |
proj4string=CRS("+proj=longlat +datum=wgs84")) | |
# Use 'over' to get _indices_ of the Polygons object containing each point | |
indices <- over(pointsSP, states_sp) | |
# Return the state names of the Polygons object containing each point | |
stateNames <- sapply(states_sp@polygons, function(x) x@ID) | |
stateNames[indices] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment