将点连接在一起以创建单线和映射输出

Joining points together to create single line and mapping output

我有以下数据:

dt1 <- data.table(
  code=c("A00111", "A00112","A00113","A00211","A00212","A00213","A00214","A00311","A00312","A00472"),
  x=c(325147,323095,596020,257409,241206,248371,261076,595218,596678,597678),
  y=c(286151,284740,335814,079727,084266,078283,062045,333889,337836,339836),
  point_id=c("P01","P02","P03","P04","P05","P06","P07","P08","P09","P10"))

sf1 <- st_as_sf(dt1, coords = c("x","y"), crs=27700, na.fail=FALSE)

我想创建一条基于 point_id 将点连接在一起的单线(因此点 P01 到 P02 到 P03 等)作为一个新的 sf 对象。然后我想通过将它附加到这样的东西来使用 tmap 可视化这条线:

tmap_mode("view")
map <- tm_shape(sf1) + tm_dots()
map

如果你总结你的 sf1 你会得到一个 MULTIPOINT-object。 do_union = F 告诉 R 不要 "union" 而是 "combine" 它们,这会保留点的顺序。所以你事先通过 id 订购它们。

最后你将 MULTIPOINT 转换为 LINESTRING

library(tmap) 
library(sf)

sf1 %>%
  summarise(do_union = F) %>%
  st_cast("LINESTRING") -> sf_line

tm_shape(sf_line) + tm_lines()

我一直在开发 sfheaders 库来帮助解决这类问题

library(sfheaders)
library(sf)

## given a data.frame, call sf_linestring() and it will return an sf object of LINESTRINGS
sf <- sf_linestring(
  obj = dt1
  , x = "x"
  , y = "y"
)
sf::st_crs( sf ) <- 27700 

sf
# Simple feature collection with 1 feature and 1 field
# geometry type:  LINESTRING
# dimension:      XY
# bbox:           xmin: 241206 ymin: 62045 xmax: 597678 ymax: 339836
# epsg (SRID):    27700
# proj4string:    +proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 +units=m +no_defs
# id                       geometry
# 1  1 LINESTRING (325147 286151, ...