Oto funkcja, która pobiera data.frame z long-longs w niższych stanach 48, a dla każdego punktu zwraca stan, w którym się znajduje.
Większość funkcji po prostu przygotowuje SpatialPoints
i SpatialPolygons
przedmiotów potrzebnych funkcji over()
w pakiecie sp
, która robi prawdziwą podnoszenia ciężkich obliczania „skrzyżowanie” punktów i wielokątów:
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
zobacz także moją odpowiedź tutaj, używając 'ggmap :: revgeocode': https://stackoverflow.com/questions/46150851/how-to-get-california- county-location-from-lat itude-and-longitude-information/46151310 # 46151310 –