R从SpatialPointsDataFrame到SpatialLines

del*_*aye 6 r point spatial line

我有一个SpatialPointsDataFrame加载

pst<-readOGR("/data_spatial/coast/","points_coast")
Run Code Online (Sandbox Code Playgroud)

我想在输出中得到一个SpatialLines,我发现了一些东西

coord<-as.data.frame(coordinates(pst))
Slo1<-Line(coord)

Sli1<-Lines(list(Slo1),ID="coastLine")
coastline <- SpatialLines(list(Sli1))
class(coastline)
Run Code Online (Sandbox Code Playgroud)

它似乎工作,但当我尝试绘图(海岸线),我有一条不应该在那里的线... 一个糟糕的海岸线

有人能帮帮我吗?shapefile就在这里!

koe*_*ker 4

我已经查看了形状文件。有一个id列,但是如果你绘制数据,似乎id不是按南北顺序排列的。创建额外的线是因为点顺序不完美,连接表中彼此相邻但在空间上彼此相距较远的点。您可以尝试通过计算点之间的距离然后按距离排序来找出数据的正确排序。

解决方法是删除那些长于特定距离(例如 500 m)的线。首先,找出连续坐标之间的距离大于此距离的位置:breaks. 然后获取两个之间的坐标子集breaks,最后为该子集创建线。您最终会得到一条由多个 ( breaks-1) 段组成的海岸线,并且没有错误的段。

# read data
library(rgdal)
pst<-readOGR("/data_spatial/coast/","points_coast")
coord<-as.data.frame(coordinates(pst))
colnames(coord) <- c('X','Y')

# determine distance between consective coordinates
linelength = LineLength(as.matrix(coord),sum=F)
# 'id' of long lines, plus first and last item of dataset
breaks = c(1,which(linelength>500),nrow(coord))

# check position of breaks
breaks = c(1,which(linelength>500),nrow(coord))

# plot extent of coords and check breaks
plot(coord,type='n')
points(coord[breaks,], pch=16,cex=1)

# create vector to be filled with lines of each subset
ll <- vector("list", length(breaks)-1)
for (i in 1: (length(breaks)-1)){
    subcoord = coord[(breaks[i]+1):(breaks[i+1]),]

# check if subset contains more than 2 coordinates
    if (nrow(subcoord) >= 2){
        Slo1<-Line(subcoord)
        Sli1<-Lines(list(Slo1),ID=paste0('section',i))
        ll[[i]] = Sli1
    }

}

# remove any invalid lines
nulls = which(unlist(lapply(ll,is.null)))
ll = ll[-nulls]
lin = SpatialLines(ll)
# add result to plot
lines(lin,col=2)

# write shapefile
df = data.frame(row.names=names(lin),id=1:length(names(lin)))
lin2 = SpatialLinesDataFrame(sl=lin, data=df)
proj4string(lin2) <- proj4string(pst)
writeOGR(obj=lin2, layer='coastline', dsn='/data_spatial/coast', driver='ESRI Shapefile')
Run Code Online (Sandbox Code Playgroud)

海岸线