R中的空间线起点和终点

the*_*ide 1 r rgdal r-raster r-sp r-sf

我试图用sp包访问线串,类似什么的起点和终点ST_StartPoint,并ST_EndPoint会产生使用psql

无论我如何尝试访问该行,我都会收到错误或 NULL 值:

> onetrip@lines[[1]][1]
Error in onetrip@lines[[1]][1] : object of type 'S4' is not subsettable

> onetrip@lines@Lines@coords
    Error: trying to get slot "Lines" from an object of a basic class ("list") with no slots

> onetrip@lines$Lines
NULL
Run Code Online (Sandbox Code Playgroud)

唯一有效的解决方案是冗长的,需要转换为SpatialLines,我只能轻松地得到第一点:

test = as(onetrip, "SpatialLines")@lines[[1]]
> test@Lines[[1]]@coords[1,]
[1] -122.42258   37.79494
Run Code Online (Sandbox Code Playgroud)

无论是str()在下面和一个简单的plot(onetrip)表演,我的数据帧不为空。

这里的解决方法是什么 - 如何返回线串的起点和终点sp

我有一个更大的第一条记录的子集SpatialLinesDataFrame

> str(onetrip)
Formal class 'SpatialLinesDataFrame' [package "sp"] with 4 slots
  ..@ data       :'data.frame': 1 obs. of  6 variables:
  .. ..$ start_time : Factor w/ 23272 levels "2018/02/01 00:12:40",..: 23160
  .. ..$ finish_time: Factor w/ 23288 levels "1969/12/31 17:00:23",..: 23288
  .. ..$ distance   : num 2.74
  .. ..$ duration   : int 40196
  .. ..$ route_id   : int 5844736
  .. ..$ vehicle_id    : int 17972
  ..@ lines      :List of 1
  .. ..$ :Formal class 'Lines' [package "sp"] with 2 slots
  .. .. .. ..@ Lines:List of 1
  .. .. .. .. ..$ :Formal class 'Line' [package "sp"] with 1 slot
  .. .. .. .. .. .. ..@ coords: num [1:3114, 1:2] -122 -122 -122 -122 -122 ...
  .. .. .. ..@ ID   : chr "0"
  ..@ bbox       : num [1:2, 1:2] -122.4 37.8 -122.4 37.8
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:2] "x" "y"
  .. .. ..$ : chr [1:2] "min" "max"
  ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
  .. .. ..@ projargs: chr "+proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs"
Run Code Online (Sandbox Code Playgroud)

seb*_*rno 5

由于您也用 sf 标记了问题,我将在 sf 中提供解决方案。请注意,您可以使用将 sp 对象转换为 sf

library(sf)
st_as_sf(sp_obj)
Run Code Online (Sandbox Code Playgroud)

创建线串

line <- st_as_sfc(c("LINESTRING(0 0 , 0.5 1 , 1 1 , 1 0.3)")) %>% 
  st_sf(ID = "poly1")   
Run Code Online (Sandbox Code Playgroud)

将每个顶点转换为点

pt <- st_cast(line, "POINT")
Run Code Online (Sandbox Code Playgroud)

开始和结束只是 data.frame 的第一行和最后一行

start <- pt[1,]
end <- pt[nrow(pt),]
Run Code Online (Sandbox Code Playgroud)

绘图 - 绿色是起点,红色是终点

library(ggplot2)
ggplot() +
  geom_sf(data = line) +
  geom_sf(data = start, color = 'green') +
  geom_sf(data = end, color = 'red') +
  coord_sf(datum = NULL)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明