Skip to content

Instantly share code, notes, and snippets.

@mhweber
Last active August 29, 2015 14:07
Show Gist options
  • Save mhweber/7e20c30cdc94512faa92 to your computer and use it in GitHub Desktop.
Save mhweber/7e20c30cdc94512faa92 to your computer and use it in GitHub Desktop.
This piece gets some summary statistics on spatial line data frame lengths within spatial polygon data frames in R
library(rgeos);library( rgdal)
polys <- readOGR('.','polys')
lines <- readOGR('.','lines')
if (proj4string(polys) == proj4string(lines){
plot(polys); plot(lines, add=T, color='Blue')
lines$LENGTHKM <- SpatialLinesLengths(lines)*0.001 # assumes lines are in projection using meters
line.sum <- over(polys, lines[6], fn=sum)
line.mean <- over(polys, lines[6], fn=mean)
line.min <- over(polys, lines[6], fn=min)
line.max <- over(polys, lines[6], fn=max)
}
if (proj4string(polys) != proj4string(lines){
polys <- spTransform(polys, CRS(proj4string(lines))
plot(polys); plot(lines, add=T, color='Blue')
lines$LENGTHKM <- SpatialLinesLengths(lines)*0.001 # assumes lines are in projection using meters
line.sum <- over(polys, lines[6], fn=sum)
line.mean <- over(polys, lines[6], fn=mean)
line.min <- over(polys, lines[6], fn=min)
line.max <- over(polys, lines[6], fn=max)
}
results <-data.frame(line.sum, line.mean, line.min, line.max)
names(results) <- c('LineSum', 'LineMean', 'LineMin','LineMax')
polys@data <- data.frame(polys@data, results)
head(polys@data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment