2012-06-19 33 views
4

我試圖用map2SpatialPolygons在顯示美國國家子集的地圖中創建內核密度圖。我不斷收到一個錯誤,說「地圖和ID的長度不一樣」。R:map2SpatialPolygons中的ID

我知道這個代碼的工作(從幫助map2SpatialPolygons):

nor_coast_poly <- map("world", "norway", fill=TRUE, col="transparent", plot=FALSE, ylim=c(58,72)) 
IDs <- sapply(strsplit(nor_coast_poly$names, ":"), function(x) x[1]) 
nor_coast_poly_sp <- map2SpatialPolygons(nor_coast_poly, IDs=IDs, proj4string=CRS("+proj=longlat +datum=wgs84")) 

這種代碼也可以運行(映射整個美國時):

usmap <- map('usa', fill=TRUE, col="transparent", resolution=0, plot=FALSE) 
uspoly <- map2SpatialPolygons(usmap, IDs=usmap$names, proj4string=CRS("+proj=longlat +datum=WGS84")) 

但是這個代碼不:

states.to.plot=c("illinois", "indiana", "ohio") 
dmap<-map("state", regions=states.to.plot, col="transparent", plot=FALSE) 
dpoly <- map2SpatialPolygons(dmap, IDs=dmap$names, proj4string=CRS("+proj=longlat +datum=WGS84")) 

它引發錯誤:

Error in map2SpatialPolygons(dmap, IDs = dmap$names, proj4string = CRS("+proj=longlat +datum=WGS84")) : 
    map and IDs differ in length 

在使用map(「state」...)時,如何獲得正確的ID?

回答

6

?map

The return value is a list with x, y, range, and names components. ... If fill is FALSE, the x and y vectors are the coordinates of successive polylines, separated by NAs. If fill is TRUE, the x and y vectors have coordinates of successive polygons, again separated by NAs.

使用默認 fill = FALSE

所以,你得到了一折線,「一幫」比你想繪製三種狀態多,這就是爲什麼你會得到上述錯誤。但是,即使使用正確數量的ID,仍然會出現錯誤,因爲map正在返回多段線而不是多邊形。

隨着fill = TRUE,你開始覺得你是多邊形後:

dmap<-map("state", regions=states.to.plot, col="transparent", plot=FALSE, fill = TRUE) 

dpoly <- map2SpatialPolygons(dmap, IDs = dmap$names, 
    proj4string=CRS("+proj=longlat +datum=WGS84")) 
+0

出色答卷,來這裏恰恰是同樣的問題。 – tomw