[R-sig-Geo] [R-sig-geo] Sum lines when they intersect polygons
Barry Rowlingson
b.rowlingson at lancaster.ac.uk
Fri Apr 8 16:32:07 CEST 2011
Slow and dirty method:
lineLengthIntersects <- function(gridpolys,linegeom){
ngrids = length(gridpolys)
ll = rep(0,ngrids)
for(i in 1:ngrids){
geomint = gIntersection(linegeom,gridpolys[i])
if(!is.null(geomint)){
ll[i] = SpatialLinesLengths(geomint,TRUE)
}
}
return(ll)
}
this returns the line length in km (TRUE in SpatialLinesLengths means
work in lat-long on a sphere and convert to km) for overlaying
polygons in gridpolys (a SpatialPolygons object) on a line geometry in
linegeom (a SpatialLines object).
there might be a better way of doing it without the loop...
here's my polygrid function for creating SpatialPolygons of a regular
grid based on x and y - use something like:
grids = polygrid(seq(0,1,len=10),seq(0,1,len=10)) to get a grid
somewhere near the greenwich meridian on the equator...
polygrid <- function(x,y){
nx = length(x)
ny = length(y)
spp = list()
ip = 1
for(ix in 1:(nx-1)){
for(iy in 1:(ny-1)){
xc=x[c(ix,ix+1,ix+1,ix,ix)]
yc=y[c(iy,iy,iy+1,iy+1,iy)]
spp[[ip]] = Polygons(list(Polygon(cbind(xc,yc))),ID=ip)
ip = ip + 1
}
}
SpatialPolygons(spp)
}
Barry
More information about the R-sig-Geo
mailing list