Skip to content

Instantly share code, notes, and snippets.

@mhweber
Created February 1, 2016 21:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhweber/d0e16ae9ff9beee798ea to your computer and use it in GitHub Desktop.
Save mhweber/d0e16ae9ff9beee798ea to your computer and use it in GitHub Desktop.
Function to build a spatial points data frame of end nodes using a spatial lines data frame - function is a modification of SpatialLinesMidPoints in the R maptools package.
SpatialLinesEndPoints = function(sldf){
Lns <- slot(sldf, "lines")
hash_lns <- sapply(Lns, function(x) length(slot(x, "Lines")))
N <- sum(hash_lns)
endpoints <- matrix(NA, ncol = 2, nrow = N)
Ind <- integer(length = N)
ii <- 1
for (i in 1:length(Lns)) {
Lnsi <- slot(Lns[[i]], "Lines")
for (j in 1:hash_lns[i]) {
Ind[ii] <- i
endpoints[ii, ] <- slot(Lnsi[[j]], "coords")[nrow(slot(Lnsi[[j]], "coords")),]
ii <- ii + 1
}
}
if (is(sldf, "SpatialLinesDataFrame")) {
df0 <- slot(sldf, "data")[Ind, ]
df <- as.data.frame(cbind(df0, Ind))
}
else df <- data.frame(Ind = Ind)
spdf <- SpatialPointsDataFrame(endpoints, data = df, proj4string = CRS(proj4string(sldf)))
return(spdf)
}
# use example assuming a spatial lines data frame called spldf loaded in session
endpoints = SpatialLinesEndPoints(spldf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment