纬度经度坐标为R中的州代码

Mic*_*ael 17 r latitude-longitude google-geocoder

有没有一种快速的方法将纬度和经度坐标转换为R中的状态代码?我一直在使用zipcode包作为查找表但是当我查询很多lat/long值时它太慢了

如果不是在R中有没有办法使用谷歌地理编码器或任何其他类型的快速查询服务?

谢谢!

Jos*_*ien 37

这是一个函数,它在较低的48个状态中获取lat-longs的data.frame,并且对于每个点,返回它所在的状态.

大部分的功能的简单地准备SpatialPointsSpatialPolygons由需要的对象over()中的功能sp包,它确实计算点和多边形的"交叉点"的真实繁重:

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(states_sp@polygons, function(x) x@ID)
    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
Run Code Online (Sandbox Code Playgroud)

  • 我不得不将wgs84改为WGS84以使这个例子起作用. (2认同)

小智 9

你可以在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)
Run Code Online (Sandbox Code Playgroud)