[R-sig-Geo] Using gIntersection to split polygons with lines

Edzer Pebesma edzer.pebesma at uni-muenster.de
Mon Jun 26 13:11:32 CEST 2017



On 26/06/17 12:56, Frederico Mestre wrote:
> Hello,
> 
> I'm trying to use gIntersection() to cut a polygon ("SpatialPolygons") with
> a line ("SpatialLinesDataFrame").
> 
> I wanted to obtain a "SpatialPolygons" object with the polygons defined by
> the lines. This is what I did:
> 
> polygons1 <- gIntersection(spgeom1=mypolygon, spgeom2=mylines)
> 
> However I get an "SpatialLines" object as an output instead of a
> "SpatialPolygons".
> 
> Am I doing something wrong? Is there any alternative?

Package sf has a function st_split() that cuts a polygon with a line,
similar to postgis' function st_split.

To use it, you'd need to build sf from source after having liblwgeom
installed; the CRAN binary builds do not have support for liblwgeom.

See https://github.com/edzer/sfr/ for instructions, and
https://github.com/edzer/sfr/issues/360 for an example.

> 
> I provide this sample code:
> 
> #Creating the polygons
> coords <- rbind(c(1,2),c(2,2),c(2,1),c(1,1))
> pol1 <- Polygon(coords)
> pol2 <- Polygons(srl=list(pol1), ID=1)
> pol3 <- SpatialPolygons(Srl=list(pol2))
> 
> #Creating the line
> l1 <- Line(rbind(c(0.5,1.5),c(2.5,1.5)))
> l2 <- Lines(list(l1),ID=1)
> l3 <- SpatialLines(list(l2))
> line1 <- SpatialLinesDataFrame(l3,data=as.data.frame(matrix(ncol=2,nrow=1)))
> 
> #Ploting both
> plot(pol3)
> plot(line1, add=TRUE)
> 
> #Intersection
> inters1 <- gIntersection(spgeom1=pol3, spgeom2=line1)
> inters1 <- gIntersection(spgeom1=line1, spgeom2=pol3)
> plot(inters1)
> class(inters1)
> 
> It only shows the lines (the object is of class "SpatialLines").
> 
> Thanks,
> Frederico
>> 
> 	[[alternative HTML version deleted]]
> 
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 

-- 
Edzer Pebesma
Institute for Geoinformatics  (ifgi),  University of Münster
Heisenbergstraße 2, 48149 Münster, Germany; +49 251 83 33081
Journal of Statistical Software:   http://www.jstatsoft.org/
Computers & Geosciences:   http://elsevier.com/locate/cageo/

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 473 bytes
Desc: OpenPGP digital signature
URL: <https://stat.ethz.ch/pipermail/r-sig-geo/attachments/20170626/1747f992/attachment.sig>


More information about the R-sig-Geo mailing list