R将邮政编码或纬度/经度转换为县 [英] R convert zipcode or lat/long to county

查看:40
本文介绍了R将邮政编码或纬度/经度转换为县的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个位置列表,其中包含每个位置的城市、州、邮编、纬度和经度.

I have a list of locations that contains a city, state, zip, latitude and longitude for each location.

我单独有一份县级经济指标清单.我玩过 zipcode 包、ggmap 包和其他几个免费地理编码网站,包括 US Gazeteer 文件,但似乎找不到匹配的方法两件.

I separately have a list of economic indicators at the county level. I've played with the zipcode package, the ggmap package, and several other free geocoding websites including the US Gazeteer files, but can't seem to find a way to match the two pieces.

目前是否有任何软件包或其他来源可以做到这一点?

Are there currently any packages or other sources that do this?

推荐答案

我最终使用了上面提到的 JoshO'Brien 的建议,发现 这里.

I ended up using the suggestion from JoshO'Brien mentioned above and found here.

我拿了他的代码并将 state 更改为 county 如下所示:

I took his code and changed state to county as shown here:

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

latlong2county <- function(pointsDF) {
    # Prepare SpatialPolygons object with one SpatialPolygon
    # per county
    counties <- map('county', fill=TRUE, col="transparent", plot=FALSE)
    IDs <- sapply(strsplit(counties$names, ":"), function(x) x[1])
    counties_sp <- map2SpatialPolygons(counties, 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, counties_sp)

    # Return the county names of the Polygons object containing each point
    countyNames <- sapply(counties_sp@polygons, function(x) x@ID)
    countyNames[indices]
}

# Test the function using points in Wisconsin and Oregon.
testPoints <- data.frame(x = c(-90, -120), y = c(44, 44))

latlong2county(testPoints)
[1] "wisconsin,juneau" "oregon,crook" # IT WORKS

这篇关于R将邮政编码或纬度/经度转换为县的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆