如何在R中无问题地将Lat-Long转换为FIPS县代码



我有数千个Lat长点,我使用此代码将其转换为FIPS县代码。

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)])

但是,问题是,它并没有将所有的lat-long转换为FIPS代码。我得到合法县的NA值。有人能帮忙吗?

还是简单地提出一个不同的解决方案?

尽管此解决方案不是基于python的,但您可以使用ruby和geokit-gem预处理数据,然后通过csv文件或其他方式将其传递给R。

请参阅本文以获取进一步的说明。

最新更新