Geekuna Matata
Geekuna Matata

Reputation: 1439

How can I convert Lat-Long to FIPS county code without problems in R?

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

Answers (1)

s2t2
s2t2

Reputation: 2686

although this solution isn't python-based, you could use ruby and the geokit gem to pre-process your data, then pass it to R via csv file or other means.

see this write-up for further instructions.

Upvotes: 1

Related Questions