2012-01-05 78 views
15

有沒有一種快速的方法來將經度和緯度座標轉換爲R中的州代碼?我一直使用zipcode包作爲查找表,但當我查詢很多緯度/長度值時,它太慢緯度經度座標到R中的州代碼

如果不是在R有任何方式使用谷歌地理編碼器或任何其他類型快速查詢服務?

謝謝!

+0

這裏也看到我的答案,使用'ggmap :: revgeocode':https://stackoverflow.com/questions/46150851/how-to-get-california-縣位置從-LAT itude-and-long-information/46151310#46151310 – 2017-09-11 08:51:12

回答

32

這是一個函數,它在低48個狀態內採用lat-long的data.frame,併爲每個點返回它所在的狀態。

大部分功能的簡單準備由spover()函數,該函數計算的點和麪的「交集」的真正繁重所需的SpatialPointsSpatialPolygons對象:

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 

latlong2state <- function(pointsDF) { 
    # Prepare SpatialPolygons object with one SpatialPolygon 
    # per state (plus DC, minus HI & AK) 
    states <- map('state', 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([email protected], function(x) [email protected]) 
    stateNames[indices] 
} 

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

latlong2state(testPoints) 
[1] "wisconsin" "oregon" # IT WORKS 
+2

我必須將wgs84更改爲WGS84才能使此示例正常工作。 – lever 2016-03-08 23:11:19

+0

@lever感謝您指出。不知道什麼時候(以及哪裏)發生了變化。無論如何,我現在編輯來解決它。 – 2016-03-08 23:17:27

2

請參閱sp包中的內容。您需要將狀態邊界作爲SpatialPolygonDataFrame。

4

你能做到這一點的R.

幾行
library(sp) 
library(rgdal) 
#lat and long 
Lat <- 57.25 
Lon <- -9.41 
#make a data frame 
coords <- as.data.frame(cbind(Lon,Lat)) 
#and into Spatial 
points <- SpatialPoints(coords) 
#SpatialPolygonDataFrame - I'm using a shapefile of UK counties 
counties <- readOGR(".", "uk_counties") 
#assume same proj as shapefile! 
proj4string(points) <- proj4string(counties) 
#get county polygon point is in 
result <- as.character(over(points, counties)$County_Name) 
+0

謝謝!這更簡單:) – 2016-08-04 13:18:02