2014-05-20 39 views
0

maptools庫中,有一個函數可將map庫中的映射轉換爲SpatialLine對象。例如:map2SpatialLines如何在maptools庫中工作?

library(maptools) 
library(maps) 
usa <- map('usa') 
llCRS <- CRS("+proj=longlat +ellps=WGS84") 
wrld_sp <- map2SpatialLines(usa, proj4string = llCRS) 

然而,地圖usa是在這個意義上,它不分別描述每個組線的位特有。相反,它似乎在座標xy聚集在一起的一切:

> str(usa) 
List of 4 
$ x : num [1:381] -101.4 -100.6 -99.6 -99 -97.3 ... 
$ y : num [1:381] 29.7 28.8 27.6 26.4 25.9 ... 
$ range: num [1:4] -124.7 -67 25.1 49.4 
$ names: chr [1:10] "main" "martha's vineyard" "nantucket island" "manhattan" ... 
- attr(*, "class")= chr "map" 

然而,功能map2SpatialLines能夠獲得各地區(10號線在此情況下的對象):

> str(wrld_sp, max.level=3) 
Formal class 'SpatialLines' [package "sp"] with 3 slots 
    [email protected] lines  :List of 10 
    .. ..$ :Formal class 'Lines' [package "sp"] with 2 slots 
    .. ..$ :Formal class 'Lines' [package "sp"] with 2 slots 
    .. ..$ :Formal class 'Lines' [package "sp"] with 2 slots 
    .. ..$ :Formal class 'Lines' [package "sp"] with 2 slots 
    .. ..$ :Formal class 'Lines' [package "sp"] with 2 slots 
    .. ..$ :Formal class 'Lines' [package "sp"] with 2 slots 
    .. ..$ :Formal class 'Lines' [package "sp"] with 2 slots 
    .. ..$ :Formal class 'Lines' [package "sp"] with 2 slots 
    .. ..$ :Formal class 'Lines' [package "sp"] with 2 slots 
    .. ..$ :Formal class 'Lines' [package "sp"] with 2 slots 
    [email protected] bbox  : num [1:2, 1:2] -124.7 25.2 -67.1 49.4 
    .. ..- attr(*, "dimnames")=List of 2 
    [email protected] proj4string:Formal class 'CRS' [package "sp"] with 1 slots 

如何它這樣做?我問這個問題的原因是因爲我希望獲取給定地區的座標作爲多邊形或Python中的線對象。

+1

其中(is.na(USA $ X))。它使用NA作爲分割的參考是不是? –

+0

哦......讓我檢查一下:-) –

+0

看來你是絕對正確的! –

回答

1

嘗試此採取同樣的數據結構

usadf <- data.frame(usa$x, usa$y) 
usa_l <- split(usadf, cumsum(is.na(usa$x))) 
with(usa_l$'0', plot(usa.x, usa.y, type = 'l')) 

simple plot

+0

非常聰明地使用cumsum。謝謝! –