Last active
March 15, 2017 19:40
-
-
Save mdsumner/642d5d06dd7c84fe54833a67ae74a4c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# candidate answer to http://gis.stackexchange.com/questions/232044/how-to-identify-which-lines-polygons-intersect-when-using-raster-data-in-r | |
library(raster) | |
library(dplyr) | |
library(rgeos) | |
##################### | |
## Create toy data ## | |
##################### | |
df <- rbind(c(1,1), c(4,4),c(3,1), c(3,4)) | |
coord_1 <- Line(rbind(c(1,1), c(4,4))) | |
coord_2 <- Line(rbind(c(3,1), c(3,4))) | |
l1 <- Lines(list(coord_1), ID = "road1") | |
l2 <- Lines(list(coord_2), ID = "road2") | |
Sl <- SpatialLines(list(l1, l2)) | |
df <- data.frame(len = gLength(Sl, byid = TRUE)) | |
#rownames(df) <- sapply(1:length(Sl), function(i) Sl@lines[[i]]@ID) | |
toy.lines <- SpatialLinesDataFrame(Sl, data = df, match.ID = FALSE) | |
toy.lines$polygon_id <- seq_len(nrow(toy.lines)) | |
toy.lines$len = rgeos::gLength(toy.lines, byid = TRUE) | |
## create the raster | |
r <- raster(extent(-0, 4, 0, 4), res = c(2, 2), crs = projection(toy.lines)) | |
r[] <- seq_len(ncell(r)) | |
library(tibble) | |
## I find this annoying having to tidy the list output, but it works fine | |
## note that if any line falls outside the raster, it will be NULL and would not | |
## work without this explicit handling | |
tabfun <- function(x) { | |
if (is.null(x)) {x <- integer(0L)} | |
tibble(cell = x) | |
} | |
(cells <- bind_rows(lapply(cellFromLine(r, toy.lines), tabfun), .id = "line")) | |
## note that "line" is character integer of the position in toy.lines | |
## due to the .id collapse for bind_rows | |
## join for complete cases | |
cells %>% right_join(tibble(cell = seq_len(ncell(r)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment