【问题标题】:Plotting lines between two sf POINT features in r在 r 中绘制两个 sf POINT 特征之间的线
【发布时间】:2020-01-28 17:00:31
【问题描述】:

我有两个空间特征:

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 中的一个点。我尝试将 POINT 转换为 LINESTRING,如下所示:

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

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

【问题讨论】:

  • 你尝试了哪些没有成功的投射?即使它没有做你想做的事情,看看它可能会有所帮助

标签: r sf


【解决方案1】:

使用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) 足以完成大部分工作,但(如文档所述)by_featurest_union 的两个参数忽略,输出是 25 对中每一对的联合来自geom1geom2 的功能。

这是一种通过坐标矩阵的更慢、更复杂的方法:

> 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    • 2013-12-11
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多