子集SpatialLinesDataFrame基于@data信息

时间:2014-05-28 16:13:19

标签: r gis geo

我有一个表示街道的SpatialLinesDataFrame。我需要找到两条街道的交汇点。

我将从How to get the intersection point of two vector?

复制一个玩具示例
library(rgdal)
library(rgeos)
a = c(1,5,2,6,3,6,3,5,7)
b = c(5,3,5,7,2,6,9,3,6)

SL1 <- SpatialLines(list(Lines(Line(cbind(seq_along(a),a)), "A")))
SL2 <- SpatialLines(list(Lines(Line(cbind(seq_along(b),b)), "B")))

# Build my own SpatialLines with both objects, couldn't find a way
# to build it from SL1 and SL2
SL <- SpatialLines(list(Lines(Line(cbind(seq_along(a),a)), "A"), Lines(Line(cbind(seq_along(b),b)), "B")))

SL.df <- SpatialLinesDataFrame(SL, data=data.frame(OBJECTID=paste(1:2), NAME=c("st 1", "av B"), row.names=row.names(SL)))

从我复制的问题的答案,我知道我可以得到交叉点

# Find intersections  
coords <- coordinates(gIntersection(SL1, SL2))

但是假设我已经阅读了带有readOGR的SL.df并且无法访问原始组件。我应该如何提取个别街道?

经过一番徘徊,我想出了

st.1 <- SpatialLines(SL.df@lines[which(row.names(SL.df) == row.names(SL.df)[which(SL.df@data$NAME == 'st 1')])])
av.B <- SpatialLines(SL.df@lines[which(row.names(SL.df) == row.names(SL.df)[which(SL.df@data$NAME == 'av B')])])
coords <- coordinates(gIntersection(st.1, av.B))

它有效,但是对各条街道的提取似乎并不优雅。有更好的方法吗?
谢谢!

1 个答案:

答案 0 :(得分:1)

有两种选择:

coordinates(gIntersection(subset(SL.df, NAME=="st 1"), 
                          subset(SL.df, NAME=="av B")))
#          x        y
# 1 1.666667 3.666667
# 1 2.400000 3.800000
# 1 4.500000 4.500000
# 1 6.000000 6.000000
# 1 7.750000 4.500000


coordinates(gIntersection(SL.df[SL.df$NAME=="st 1",], 
                          SL.df[SL.df$NAME=="av B",]))
#          x        y
# 1 1.666667 3.666667
# 1 2.400000 3.800000
# 1 4.500000 4.500000
# 1 6.000000 6.000000
# 1 7.750000 4.500000