2017-02-20 72 views
1

我試圖獲得紐約地區經緯度座標的郵政編碼如何批量反轉R中的地理編碼?

我試圖使用谷歌的反向地理編碼器API,但每天限制在2500次點擊,因此可以批量處理我的數據幀。

接下來,我嘗試使用帶有數據集郵編的庫(zipcode),但無法將緯度經度與火車數據集的座標進行匹配,因爲所有緯度經度座標都不在數據集中。

此外,雖然使用KNN來預測數據集的郵政編碼,但無法獲得正確的結果。

zipcode_latlon = zipcode[zipcode$state=="NY",c(1,4,5)] 
train_latlon = train_data[,c("latitude","longitude")] 
zip1 = rep(10007, nrow(train_latlon)) 
zip1 = as.character(zip1) 
train_latlon = cbind(zip1, train_latlon) 
colnames(train_latlon) = c("zip","latitude","longitude") 
knn_fit = knn(zipcode_latlon, train_latlon,zipcode_latlon$zip, k=1) 

需要知道如何我可以從Lat Long網批量獲得郵編,任何方法都好於R.

+0

是否有效? –

+0

謝謝!是的,它爲我工作。 但是很難理解Shape文件格式。 無法理解spTransform()中的屬性 –

+0

原始shapefile位於座標參考系NAD83中。 spTransform只是給'zips'一個不同的參考系統 - 在這個例子中是WGS84。點和多邊形具有相同的CRS是很重要的。也可以按照導入後的方式保留'zips',然後用'+ proj = longlat + datum = NAD83 + no_defs + ellps = GRS80 + towgs84 = 0,0,0給'spdf' NAD83 CRS '。無論如何,沒有參考系統,空間數據就毫無意義。 –

回答

1

我想你會對此錯誤的方式。你可以找到經/緯度的郵政編碼座標沒有地理編碼器 - 所有你需要的是下載美國郵編SHAPEFILE here,然後做一個空間連接:

library(sp) 
library(rgdal) 

#import zips shapefile and transform CRS 
zips <- readOGR("cb_2015_us_zcta510_500k.shp") 
zips <- spTransform(zips, CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")) 

#here is a sample with three cities in New York State and their coordinates  
df <- as.data.frame(matrix(nrow = 3, ncol =3)) 
colnames(df) <- c("lat", "lon", "city") 

df$lon <- c(43.0481, 43.1610, 42.8864) 
df$lat <- c(-76.1474, -77.6109,-78.8784) 
df$city <- c("Syracuse", "Rochester", "Buffalo") 

df 
     lat  lon  city 
1 -76.1474 43.0481 Syracuse 
2 -77.6109 43.1610 Rochester 
3 -78.8784 42.8864 Buffalo 

#extract only the lon/lat     
xy <- df[,c(1,2)] 

#transform coordinates into a SpatialPointsDataFrame 
spdf <- SpatialPointsDataFrame(coords = xy, data = df, proj4string = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")) 

#subset only the zipcodes in which points are found 
zips_subset <- zips[spdf, ] 

#NOTE: the column in zips_subset containing zipcodes is ZCTA5CE10 
#use over() to overlay points in polygons and then add that to the original dataframe 

df$zip <- over(spdf, zips_subset[,"ZCTA5CE10"]) 

瞧!你有每個點的郵政編碼

df 
     lat  lon  city ZCTA5CE10 
1 -76.1474 43.0481 Syracuse  13202 
2 -77.6109 43.1610 Rochester  14604 
3 -78.8784 42.8864 Buffalo  14202 
+0

謝謝!現在對我的作品 但無法解釋 CRS( 「+ PROJ = longlat +基準= WGS84 + ellps = WGS84 + towgs84 = 0,0,0」) 也許我不明白的空間數據文件。我們如何看待這個? –