R конвертировать zipcode или lat/long в графство
У меня есть список местоположений, которые содержат город, штат, почтовый индекс, широту и долготу для каждого местоположения.
У меня есть список экономических показателей на уровне графства. Я играл с пакетом zipcode
, пакетом ggmap
и несколькими другими бесплатными сайтами геокодирования, включая файлы Gazeteer США, но не может найти способ сопоставить две части.
Есть ли в настоящее время какие-либо пакеты или другие источники, которые это делают?
Ответы
Ответ 1
В итоге я воспользовался предложением JoshO'Brien
упомянутым выше, и нашел его здесь.
Я взял его код и изменил state
на county
как показано здесь:
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([email protected], function(x) [email protected])
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
Ответ 2
Соответствие Zipcodes для округов сложно. (Некоторые почтовые индексы охватывают более одного округа, а иногда и более одного состояния. Например 30165)
Я не знаю какого-либо конкретного пакета R, который может соответствовать этим требованиям для вас.
Однако вы можете получить хорошую таблицу из Центра данных переписи Миссури.
Для извлечения данных вы можете использовать следующие данные: http://bit.ly/S63LNU
Пример вывода может выглядеть так:
state,zcta5,ZIPName,County,County2
01,30165,"Rome, GA",Cherokee AL,
01,31905,"Fort Benning, GA",Russell AL,
01,35004,"Moody, AL",St. Clair AL,
01,35005,"Adamsville, AL",Jefferson AL,
01,35006,"Adger, AL",Jefferson AL,Walker AL
...
Обратите внимание на County2.
описание метаданных можно найти здесь.
county
The county in which the ZCTA is all or mostly contained. Over 90% of ZCTAs fall entirely within a single county.
county2
The "secondary" county for the ZCTA, i.e. the county which has the 2nd largest intersection with it. Over 90% of the time this value will be blank.
См. также коды округа ANSI
http://www.census.gov/geo/www/ansi/ansi.html
Ответ 3
Я думаю, что пакет "noncensus" полезен.
соответствует тому, что я использую для сопоставления zipcode с округом
### code for get county based on zipcode
library(noncensus)
data(zip_codes)
data(counties)
state_fips = as.numeric(as.character(counties$state_fips))
county_fips = as.numeric(as.character(counties$county_fips))
counties$fips = state_fips*1000+county_fips
zip_codes$fips = as.numeric(as.character(zip_codes$fips))
# test
temp = subset(zip_codes, zip == "30329")
subset(counties, fips == temp$fips)
Ответ 4
Простая опция заключается в использовании функции geocode()
в ggmap
с опцией output="more"
или output="all
.
Это может принимать гибкий ввод, такой как адрес или lat/lon, и возвращает адрес, город, графство, страну, страну, почтовый индекс и т.д. в качестве списка.
require("ggmap")
address <- geocode("Yankee Stadium", output="more")
str(address)
$ lon : num -73.9
$ lat : num 40.8
$ type : Factor w/ 1 level "stadium": 1
$ loctype : Factor w/ 1 level "approximate": 1
$ address : Factor w/ 1 level "yankee stadium, 1 east 161st street, bronx, ny 10451, usa": 1
$ north : num 40.8
$ south : num 40.8
$ east : num -73.9
$ west : num -73.9
$ postal_code : chr "10451"
$ country : chr "united states"
$ administrative_area_level_2: chr "bronx"
$ administrative_area_level_1: chr "ny"
$ locality : chr "new york"
$ street : chr "east 161st street"
$ streetNo : num 1
$ point_of_interest : chr "yankee stadium"
$ query : chr "Yankee Stadium"
Другое решение - использовать файл формы переписи и ту же команду over()
из вопроса. Я столкнулся с проблемой, используя базовую карту maptools: поскольку она использует базу данных WGS84, в Северной Америке точки, расположенные в нескольких милях от побережья, были неправильно отображены и около 5% моего набора данных не совпадали.
попробуйте это, используя sp
пакет и файлы формы TIGERLine Census
counties <- readShapeSpatial("maps/tl_2013_us_county.shp", proj4string=CRS("+proj=longlat +datum=NAD83"))
# Convert pointsDF to a SpatialPoints object
pointsSP <- SpatialPoints(pointsDF, proj4string=CRS("+proj=longlat +datum=NAD83"))
countynames <- over(pointsSP, counties)
countynames <- countynames$NAMELSAD