在R语言中绘制两个sf POINT要素之间的连线

9

我有两个空间特征:

library(sf)

points1 <- data.frame(foo = seq(15, 75, 15), 
                     long = c(-85, -80, -78, -75, -82), 
                     lat = c(34, 36, 37, 38, 35)) %>% 
    st_as_sf(coords = c('long', 'lat'), crs = 4326) 

points2 <- data.frame(bar = seq(15, 75, 15), 
                     long = c(85, 80, 78, 75, 82), 
                     lat = c(30, 32, 34, 36, 38)) %>% 
    st_as_sf(coords = c('long', 'lat'), crs = 4326) 

cbind(points1, points2) -> df

这样做会产生以下结果:
  foo bar       geometry    geometry.1
1  15  15 POINT (-85 34) POINT (85 30)
2  30  30 POINT (-80 36) POINT (80 32)
3  45  45 POINT (-78 37) POINT (78 34)
4  60  60 POINT (-75 38) POINT (75 36)
5  75  75 POINT (-82 35) POINT (82 38)

我想在df中点对之间绘制一条线-从geometry中的一个点到geometry.1中的一个点。我尝试将这些点转换为一个LINESTRING,方法如下:

df %>% summarise(do_union=F) %>% st_cast("LINESTRING") %>% plot()

但是这似乎不起作用。我得到的是一条连续的线,而我想要的是五个单独的行。


你尝试过哪些强制转换但不起作用?即使它不能完成你想要的功能,让我们看看也可能会有所帮助。 - camille
1个回答

11

使用 mapply 函数通过成对合并几何列中的点来创建一条线字符串:

> st_sfc(mapply(function(a,b){st_cast(st_union(a,b),"LINESTRING")}, df$geometry, df$geometry.1, SIMPLIFY=FALSE))
Geometry set for 5 features 
geometry type:  LINESTRING
dimension:      XY
bbox:           xmin: -85 ymin: 30 xmax: 85 ymax: 38
epsg (SRID):    NA
proj4string:    NA
LINESTRING (-85 34, 85 30)
LINESTRING (-80 36, 80 32)
LINESTRING (-78 37, 78 34)
LINESTRING (-75 38, 75 36)
LINESTRING (-82 35, 82 38)

起初我认为st_union(geom1, geom2, by_feature=TRUE)足以完成大部分工作,但是(如文档所述),当在st_union中使用两个参数时,by_feature选项被忽略,输出将是从geom1geom2的25对要素的并集。

以下是通过坐标矩阵进行的较慢、较麻烦的方法:

> coords = cbind(st_coordinates(df$geometry), st_coordinates(df$geometry.1))

按行构建线串:

> linestrings = st_sfc(
     lapply(1:nrow(coords),
           function(i){
             st_linestring(matrix(coords[i,],ncol=2,byrow=TRUE))
           }))

请参见:

> plot(linestrings)

如果您想将数据框中的(第一个)点几何图形替换为线条,则:

输入图像描述

> st_geometry(df) = linestrings

我建议您将答案更新为 st_union(geom1, geom2, by_feature=TRUE) |> st_cast("LINESTRING") 对我来说,这个方法似乎比您使用的mapply一行代码更简短且更易读。 - undefined
我还想指出矩阵选项可以保持顺序,如果行的起始和结束很重要的话。@spacedman - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接