15

I am guessing there is a simple solution to the problem I have been having, but I am having some trouble.

I am trying to convert the following map object:

require(maps)
usa <- map("state")

into a SpatialPolygon object using the map2SpatialPolygons function:

require(maptools)
usa.sp <- map2SpatialPolygons(usa, IDs=usa$names,proj4string=CRS("+proj=longlat"))

I keep getting the following error:

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

After some research, it looks like the IDs have length 63 and the map object has length 169 after applying the function .NAmat2xyList(cbind(map$x, map$y)) (for which I cannot find the source to).

Anyone have any ideas? Here is the structure of the usa map object:

> str(usa)
List of 4
 $ x    : num [1:1705] -88.4 -88.1 -88 -87.9 -87.8 ...
 $ y    : num [1:1705] 30.4 30.4 30.8 30.6 30.3 ...
 $ range: num [1:4] -124.7 -67 25.1 49.4
 $ names: chr [1:63] "alabama" "arizona" "arkansas" "california" ...
 - attr(*, "class")= chr "map"
Mike.Gahan
  • 4,565
  • 23
  • 39

2 Answers2

16

Just found some code in the text "Applied Spatial Data Analysis with R". It works great!

require(maps)
usa <- map("state", fill = TRUE)

require(sp)
require(maptools)
IDs <- sapply(strsplit(usa$names, ":"), function(x) x[1])
usa <- map2SpatialPolygons(usa, IDs=IDs, proj4string=CRS("+proj=longlat +datum=WGS84"))
Mike.Gahan
  • 4,565
  • 23
  • 39
  • When using the map by specifying the world-database and access the countries by their region name, regions could imho be accessed in a more general way: germany <- map("world",regions="Germany",fill=TRUE) As I understand only a limited set of databases is defined in the way you called it, Germany for example isn't. Nevertheless, your answer saved my day! – Exocom Nov 04 '15 at 15:43
7

Polygons have surface (area), therefore the key argument is fill = TRUE in

usa <- map('state', fill = TRUE)

Changing the argument value to TRUE stops the error message.

Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
DDB
  • 71
  • 1
  • 1
  • +1 Great point. It would be helpful if the ?map reference specified that the "fill" argument had this downstream effect. The way it is currently written (version 2.3-11), it reads like it only affects how the map is drawn on the screen. – Arthur Sep 17 '15 at 14:53