如何有效地从点创建线串?

How to efficiently create Linestrings from points?

我在两个单独的数据框中有几何点。我想要做的是用一条线连接点(稍后在地图上),这就是为什么我想为这些数据框中的每对点创建线串。我是这样做的:

coordsCust <- table %>%
  st_as_sf(coords = c("lonCust","latCust"), crs = 4326)

coordsApp <- table %>%
  st_as_sf(coords = c("lonApp","latApp"), crs = 4326) %>%
  st_geometry()

和线串:

lines <- st_sfc(mapply(function(a,b){
  st_cast(st_union(a,b),"LINESTRING")}, 
  coordsCust$geometry, coordsApp$geometry, SIMPLIFY=FALSE))

此代码有效,我可以为每对点逐行创建线串:

LINESTRING (14.035 51.65182, 14.33418 53.53346)
LINESTRING (20.42767 49.98073, 16.62978 52.31037)
LINESTRING (20.18762 50.03337, 16.62978 52.31037)
LINESTRING (19.04625 49.79234, 16.62978 52.31037)
LINESTRING (21.35808 50.92382, 16.62978 52.31037)

问题是对于 30 000 行,此解决方案的工作速度非常慢 - 大约 21 秒。还有其他方法可以从点创建线串吗?运行速度更快的东西?我在网上搜索了一些解决方案但徒劳无功。我读过一些关于将 sf 转换为矩阵并使用 pmap 的内容,但不知道如何在此处实现它。

更新: 如果我想使用 sfheaders::sf_linestring 函数,我需要连接来自两个数据集的几何图形。我这样做:

df <- cbind(coordsCust,coordsApp)

最终数据框(我展示了其中最重要的部分)如下所示:

不幸的是 sf_linestring 在此数据帧上无法正常工作。我需要在每行的点之间分别创建线串,如屏幕上所示。

没有示例数据集,很难完全回答您的问题。但是如果你能把你的 data.frame 变成 'long' 形式,那么 sfheaders 可以瞬间做到这一点

n <- 30000
df <- data.frame(
  x = rnorm(n)
  , y = rnorm(n)
)

df$id <- rep(1:(n/2), each = 2)

sfheaders::sf_linestring(
  obj = df
  , x = "x"
  , y = "y"
  , linestring_id = "id"
)

# Simple feature collection with 15000 features and 1 field
# geometry type:  LINESTRING
# dimension:      XY
# bbox:           xmin: -4.297631 ymin: -4.118291 xmax: 3.782847 ymax: 4.053399
# CRS:            NA
# First 10 features:
#   id                       geometry
# 1   1 LINESTRING (0.2780517 0.243...
# 2   2 LINESTRING (0.4261505 2.503...
# 3   3 LINESTRING (0.8662821 -0.11...
# 4   4 LINESTRING (-0.5335952 -0.1...
# 5   5 LINESTRING (1.154309 -1.352...
# 6   6 LINESTRING (0.05512324 -0.4...
# 7   7 LINESTRING (1.945868 -0.744...
# 8   8 LINESTRING (0.0427066 -0.08...
# 9   9 LINESTRING (0.06738045 0.41...
# 10 10 LINESTRING (0.4128964 -0.04...