Skip to content

Instantly share code, notes, and snippets.

@arcaravaggi
Last active October 3, 2017 13:00
Show Gist options
  • Save arcaravaggi/2b24abfb39b8ec4dd80b52f3e69280e4 to your computer and use it in GitHub Desktop.
Save arcaravaggi/2b24abfb39b8ec4dd80b52f3e69280e4 to your computer and use it in GitHub Desktop.
Intersects SpatialLine and SpatialPolygon objects and produces total line length and density per polygon ID.
# Calculate total line length and density for a given set of polygons
#
# Intersects SpatialLine and SpatialPolygon objects, calculates individual line length,
# appends to dataframe extracted from intersect object and summarises by polygon ID.
# If density is not required, do not specify area parameter `a`.
#
# The function assumes a spatial projection system where distance is given in metres.
#
# E.g.
# sp1 = object of class SpatialLine/SpatialLineDataFrame
# sp2 = object of class SpatialPolygon/SpatialPolygonDataFrame
# id = name of polygon column for summary. Currently requires a-priori insertion into the function
# a = area of polygon (default = 0)
#
# E.g.
# df <- len.dens(lines, polygon, id = t$grouping, a = pi*4.58^2)
require(rgeos)
require(plyr)
spLine.ld <- function(sp1, sp2, id, a = 0){
r <- raster::intersect(sp1, sp2)
y <- gLength(r, byid = TRUE)
t <- r@data
t["r_length"] <- y/1000
if(a == 0){
dat <- ddply(t,.(FID_1),summarize,r_length=sum(r_length))
} else{
dat <- ddply(t,.(FID_1),summarize,r_length=sum(r_length))
dat["r_dens"] <- dat$r_length / a
}
dat
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment