如何接收 R 中相交 SpatialLines 的差异?

How to receive differences of intersecting SpatialLines in R?

如何只接收相交SpatialLines的差异的SpatialLines列表?

创建空间线:

#from the sp vignette:
l1 = cbind(c(1,2,3,4),c(3,2,2,4))
rownames(l1) = letters[1:4]
l2 = cbind(c(2,2,3,3),c(3,2,2,5))
rownames(l2) = letters[1:4]
l3 = cbind(c(1,2,3,4),c(1,2,2,1))
rownames(l3) = letters[1:4]
Sl1 = Line(l1)
Sl2 = Line(l2)
Sl3 = Line(l3)
Ll1 = Lines(list(Sl1), ID="a")
Ll2 = Lines(list(Sl2), ID="b")
Ll3 = Lines(list(Sl3), ID="c")
Sl = SpatialLines(list(Ll1,Ll2,Ll3))

生成的 SpatialLines ("Sl") 显示交叉点和差异点。 接收list所有SpatialLines的差异可以这样实现:

C = combn(1:length(Sl),2)
C2 = cbind(C,C[2:1,])
MyDiffs = apply(C2, 2, function(x){gDifference(Sl[x[1]], Sl[x[2]])})

spacedman´s answer to this question

只寻找相交空间线的差异。 我在想如果条件 gIntersect=TRUE 然后应用 gDifference()。但是,我找不到在 R 中执行此操作的方法。 也许有更聪明的解决方案...

编辑: 的答案有效,但所有差异出现两次。 以移除下三角部分的方式操作矩阵导致保留一些双倍差异而其他部分被移除的结果。

library("reshape2")
# compute intersection matrix by ID
intersections <- gIntersects(Sl, byid=TRUE)
# set lower triangular part of matrix NA
intersections[lower.tri(intersections, diag = TRUE)] <- NA
# melt matrix into edge list (+remove NA)
intersections <- melt(intersections, na.rm=TRUE)
# compute differences
MyDiffs = apply(intersections, 1, function(x){gDifference(Sl[x[1]], Sl[x[2]])})

有什么建议吗?

只需将 gIntersectsbyid=Treshape2 中的 melt 函数一起使用:

library("reshape2")
# compute intersection matrix by ID
intersections <- gIntersects(Sl, byid=T)
# melt matrix into edge list
intersections <- melt(intersections)
# keep only intersecting lines, remove diagonals
intersections <- subset(intersections, Var1 != Var2 & value)
# compute differences
MyDiffs = apply(intersections, 1, function(x){gDifference(Sl[x[1]], Sl[x[2]])})