The 'TopologyException: Input geom 1 is invalid' self-intersection error which arises from invalid polygon geometries has been widely discussed. However, I haven't found a convenient solution on the web that solely relies on R functionality.
For instance, I have managed to create a 'SpatialPolygons' object from the output of map("state", ...)
following Josh O'Brien's nice answer here.
library(maps)
library(maptools)
map_states = map("state", fill = TRUE, plot = FALSE)
IDs = sapply(strsplit(map_states$names, ":"), "[[", 1)
spydf_states = map2SpatialPolygons(map_states, IDs = IDs, proj4string = CRS("+init=epsg:4326"))
plot(spydf_states)
The problem with this widely applied dataset is now that self-intersection occurs at the point given below.
rgeos::gIsValid(spydf_states)
[1] FALSE
Warning message:
In RGEOSUnaryPredFunc(spgeom, byid, "rgeos_isvalid") :
Self-intersection at or near point -122.22023214285259 38.060546477866055
Unfortunately, this problem prevents any further use of 'spydf_states', e.g. when calling rgeos::gIntersection
. How can I solve this issue from within R?
plot(spydf_states, xlim=c(-122.1,-122.3),ylim=c(38,38.1))
you'll see there's no "seemingly" about it - there's a self-intersection.