Ada*_*ith 5 gis maps r r-maptools r-sp
如何将夏威夷和阿拉斯加添加到以下代码(摘自Josh O'Brien在这里的答案:R中的国家代码的纬度经度坐标)?
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 Alaska (ak) and Hawaii (hi)
ak <- data.frame(lon = c(-151.0074), lat = c(63.0694))
hi <- data.frame(lon = c(-157.8583), lat = c(21.30694))
nc <- data.frame(lon = c(-77.335), lat = c(34.671))
latlong2state(ak)
latlong2state(hi)
latlong2state(nc)
Run Code Online (Sandbox Code Playgroud)
在latlong2state(ak)和latlong2state(hi)代码返回NA,但如果代码被修改正确,阿拉斯加和夏威夷将返回结果。
任何帮助表示赞赏!
您需要使用具有50个州的地图,您正在使用的州states <- map('state', fill=TRUE, col="transparent", plot=FALSE)没有夏威夷州和阿拉斯加。
例如,您可以从此处下载20m美国地图,并将其解压缩到当前目录中。然后,您应该cb_2013_us_state_5m在R当前目录中有一个名为的文件夹。
我修改了您发布的代码,为夏威夷和Alsaka工作,没有尝试其他方法。
library(sp)
library(rgeos)
library(rgdal)
# 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) {
states <-readOGR(dsn='cb_2013_us_state_5m',layer='cb_2013_us_state_5m')
states <- spTransform(states, CRS("+proj=longlat"))
pointsSP <- SpatialPoints(pointsDF,proj4string=CRS("+proj=longlat"))
# Use 'over' to get _indices_ of the Polygons object containing each point
indices <- over(pointsSP, states)
indices$NAME
}
# Test the function using points in Alaska (ak) and Hawaii (hi)
ak <- data.frame(lon = c(-151.0074), lat = c(63.0694))
hi <- data.frame(lon = c(-157.8583), lat = c(21.30694))
latlong2state(ak)
latlong2state(hi)
Run Code Online (Sandbox Code Playgroud)