I have a list (imported from Stata dta file) containing entries defining spacial polygons for a map, to give an idea:
> typeof(aux3)
[1] "list"
> mode(aux3)
[1] "list"
> head(aux3)
_ID _X _Y
1 1 NA NA
2 1 -22.23933 64.56315
3 1 -22.25667 64.56053
4 1 -22.25026 64.56653
5 1 -22.27167 64.57319
6 1 -22.30311 64.55409
> tail(head(aux3,20000))
_ID _X _Y
19995 2 21.21593 60.24696
19996 2 21.21650 60.24337
19997 2 21.23972 60.24913
19998 2 21.22203 60.23304
19999 2 21.21618 60.23332
20000 2 21.22092 60.23930
> #etc.
I would like to convert this into a data structure with which I can work to create a map (without larger difficulty and without needing extensive expertise, never having done that before) in R. I inferred that the SpacialPolygons type of the sp package is the easiest choice. Further, from the definition, it seemed that the SpacialPolygons method (defined in this package, see the package's documentation, page 79) is the correct method to convert from list to this data type.
Unfortunately, the method is not that straightforward to work with and I need some help. My (naive) attempt yields an error that I do not understand and that does not turn up any interesting results in a google search:
> library(maptools)
Loading required package: sp
Checking rgeos availability: FALSE
Note: when rgeos is not available, polygon geometry computations in maptools depend on gpclib,
which has a restricted licence. It is disabled by default;
to enable gpclib, type gpclibPermit()
> SP<-SpatialPolygons(aux3)
Error in SpatialPolygons(aux3) :
cannot get a slot ("area") from an object of type "integer"
Can the list above be converted to SpacialPolygon? If so, how? If not, what format should I choose instead? Thanks.
If you just want to draw the map, you could use ggplot. I can't test this since I don't have your data, but should work.
library(ggplot2)
aux_df <- data.frame(aux3)
# as per comment: the list-to-dataframe conversion prepends the column names with X
ggplot(aux_df, aes(x=X_X, y=X_Y, group=X_ID) +
geom_polygon(color='black', fill=NA) +
coord_map() +
theme_classic()
The above assumes the list aux3
has longitude and latitude in _X
and _Y
and polygons defined by _ID
. It applies a mercator projection by default, but you can change this using different arguments to coord_map()
.
Here's a working example using a map of ohio counties (arbitrary choice).
library(ggplot2)
ohio_poly <- map_data('county', region='ohio')
ggplot(ohio_poly, aes(x=long, y=lat, group=group)) +
geom_polygon(color='black', fill=NA) +
coord_map() +
theme_classic()