R从SpatialPointsDataFrame到SpatialLines

时间:2014-03-23 21:58:21

标签: r line point spatial

我有一个带

的SpatialPointsDataFrame加载
pst<-readOGR("/data_spatial/coast/","points_coast")

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

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

Sli1<-Lines(list(Slo1),ID="coastLine")
coastline <- SpatialLines(list(Sli1))
class(coastline)

它似乎有用,但是当我尝试绘图(海岸线)时,我有一条不应该在那里的线...... a bad coastline

有人可以帮助我吗? The shapefile is here

1 个答案:

答案 0 :(得分:4)

我看过shapefile。有一个id列,但是如果你绘制数据,似乎id不是从南北或其他东西排序的。创建额外的线是因为点顺序不完美,连接表中彼此相邻的点,但在空间方面彼此相距很远。您可以尝试通过计算点之间的距离然后按距离排序来确定数据的正确排序。

解决方法是删除长度超过一定距离的那些行,例如500米..首先,找出连续坐标之间的距离大于此距离: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')

coastline