I have a large SpatialLinesDataFrame (~23000 features) and a SpatialPolygonsDataFrame (8 features). I want to make 8 new variables, each with the lines that are on the same locations as the polygons. This should be easy, but I can't find the right way.

I tried the sp::over method, but it returns the error: Don't Kont how to get path data from object of class data.frame. I assume that this is because in the help section there is not a method where x = SpatialLinesDataFrame and y = SpatialPolygonsDataFrame.

1 Answer 1


In the future, please ask a good question by providing some example data as below:

cds <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45))
lines <- spLines(cds, cds-20, cds+20, attr=data.frame(Lid=1:3))

p1 <- rbind(c(180,20), c(140,-55), c(10, 0), c(140,60), c(180,20))
p2 <- rbind(c(-10,0), c(-140,-60), c(-160,0), c(-140,55), c(-10,0))
pols <- spPolygons(p1, p2, attr=data.frame(Pid=1:2))

lines(lines, col='blue')

Now you can do

x <- intersect(lines, pols)

You can use subsetting to get the lines that match a specific polygon

LP1 <- x[x$Pid == 1, ]

Perhaps wrapped in a lapply to get a list

p <- lapply(1:length(pols), function(i) x[x$Pid == i, ])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.