从R中的坐标列表在"简单特征"中创建多条线



我正在尝试检测成对的对象(树(是被道路隔开还是位于它们的同一侧。我已经下载了我的道路网络,并且认为我或多或少了解如何使用st_intersects。因此,我所缺少的只是我正在考虑的成对树木之间的线段,以便测试与道路的交叉口。。

然而,我似乎不知道如何在我的对象之间创建线条。我有大量的对(300K+(,所以必须能够通过编程来实现这一点,而我发现的所有示例似乎都是"手工编码的"。

假设以下两个矩阵,包含每对的"原点"one_answers"目的地"的坐标。

orig = matrix(runif(20),ncol=2)
dest = matrix(runif(20),ncol=2)

在这个例子中,我需要创建10行:一行在orig[1,]dest[1,]之间,另一行(不同的(在orig[2,]dest[2,]之间,等等。我的理解是我应该使用st_multilinestring,但我不知道如何制定调用。通常,我要么以"XYZM"点结束,要么以一条从orig[1,]开始、经过所有其他坐标后终止于dest[10,]的多段线结束。当它不是这些结果之一时,它就是一大堆错误。

st_multilinestring是我应该使用的吗?如果是,如何做到这一点?谢谢

以下是使用library(sfheaders)构造sfc/sf对象的方法

library(sf)
library(sfheaders)
## If you add a pseudo-id column
orig <- cbind( orig, 1:nrow( orig ) )
dest <- cbind( dest, 1:nrow( dest ) )
## you can bind these matrices together
m <- rbind( orig, dest )
## set the order by the 'id' column
m <- m[ order( m[,3] ), ]
## then use `sfheaders` to create your linestrings
sfc <- sfheaders::sfc_linestring(
obj = m
, linestring_id = 3 ## 3rd column
)
sfc
# Geometry set for 10 features 
# geometry type:  LINESTRING
# dimension:      XY
# bbox:           xmin: 0.01952919 ymin: 0.04603703 xmax: 0.9172785 ymax: 0.9516615
# epsg (SRID):    NA
# proj4string:    NA
# First 5 geometries:
# LINESTRING (0.7636528 0.2465392, 0.05899529 0.7...
# LINESTRING (0.6435893 0.9158161, 0.01952919 0.1...
# LINESTRING (0.05632407 0.3106372, 0.03306822 0....
# LINESTRING (0.1978259 0.07432209, 0.2907429 0.0...
# LINESTRING (0.1658199 0.6436758, 0.1407145 0.75...

使用lapply在源矩阵和目的矩阵的行上循环,并创建LINESTRING对象的向量:

> lines = do.call(st_sfc,
lapply(
1:nrow(orig),
function(i){
st_linestring(
matrix(
c(orig[i,],dest[i,]), ncol=2,byrow=TRUE)
)
}
)
)

这给了你这个:

> lines
Geometry set for 10 features 
geometry type:  LINESTRING
dimension:      XY
bbox:           xmin: 0.06157865 ymin: 0.007712881 xmax: 0.967166 ymax: 0.9864812
epsg (SRID):    NA
proj4string:    NA
First 5 geometries:
LINESTRING (0.6646269 0.1545195, 0.8333102 0.40...
LINESTRING (0.5588124 0.5166538, 0.3213998 0.08...
LINESTRING (0.06157865 0.6138778, 0.06212246 0....
LINESTRING (0.202455 0.4883115, 0.5569435 0.986...
LINESTRING (0.3120373 0.8189916, 0.8499419 0.73...

让我们检查一下,我们都做对了。第四行从哪里来,往哪里去?

> orig[4,]
[1] 0.2024550 0.4883115
> dest[4,]
[1] 0.5569435 0.9864812

其看起来像第四LINESTRING输出中的坐标。

然后,您可以将st_intersects与另一组功能结合起来,并查看其中哪些功能与它们交叉。

(您可能还需要为其添加坐标系…(

最新更新