R: identifiers in map2SpatialPolygons

I am trying to use map2SpatialPolygons to create a graph of core density on a map showing a subset of US states. I continue to be mistaken in saying that "map and identifiers differ in length."

I know this code works (from the help for 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")) 

this code also works (when displaying the whole US):

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

but this code does not:

 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")) 

It gives an error:

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

How to get identifiers when using a card ("state" ...)?

+4
source share
1 answer

From ?map :

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

So, by default fill = FALSE you get a bunch of polylines, a bunch is more than the three states you wanted to build, and why you get the error above. However, even with the correct number of identifiers, you still get an error, since map returns polylines instead of polygons.

With fill = TRUE you get the polygons you use:

 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")) 
+6
source

All Articles