如何在R中接收相交的SpatialLines的差异? [英] How to receive differences of intersecting SpatialLines in R?

查看:73
本文介绍了如何在R中接收相交的SpatialLines的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to receive a list of SpatialLines of the differences of the intersecting SpatialLines only?

创建SpatialLines:

create 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")显示相交和差异.可以通过以下方式获得列表中所有SpatialLines的差异:

resulting SpatialLines ("Sl") show intersections and differences. Receiving the differences of all SpatialLines of the list can be achieved like this:

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对这个问题的回答

仅查找相交的SpatialLines的差异.我在考虑类似条件 gIntersect = TRUE 然后应用 gDifference().但是,我找不到在R中执行此操作的方法.也许有一个更聪明的解决方案...

Looking for the differences of the intersecting SpatialLines only. I was thinking about something like if the condition gIntersect=TRUE then apply gDifference(). However, I can´t find a way to do that in R. Maybe there´s a smarter solution...

修改: bogdata 的答案有效,但是所有差异都出现两次.以删除下部三角形部分的方式来处理矩阵会导致以下结果:保留一些加倍的差,而删除其他的差.

The answer of bogdata works, but all differences appear twice. Manipulating the matrix in a way that the lower triangular part get removed led to the result that some doubled differences are kept while others get removed.

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]])})

有什么建议吗?

推荐答案

只需在 byid = T melt 函数中使用 gIntersects reshape2 :

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]])})

这篇关于如何在R中接收相交的SpatialLines的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆