Reputation: 1439
I have thousands of Lat-long points and I used this code to convert it into FIPS county codes.
latlong2county <- function(pointsDF) {
# Prepare SpatialPolygons object with one SpatialPolygon
# per state (plus DC, minus HI & AK)
states <- map('county', 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]
}
data(county.fips)
latlon <- data.frame(all$lon,all$lat)
county<-latlong2county(latlon)
fips<-with(county.fips, fips[match(county, polyname)])
But, the problem with this is it is not converting all lat-longs to FIPS codes. I get NA values for legitimate counties. Can anyone help with it?
Or simply suggest a different solution?
Upvotes: 0
Views: 2097