gpt4 book ai didi

R 从 SpatialPointsDataFrame 到 SpatialLines

转载 作者:行者123 更新时间:2023-12-04 15:22:47 25 4
gpt4 key购买 nike

我有一个 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)

它似乎有效,但是当我尝试 plot(coaSTLine) 时,我有一条不应该在那里的线......
a bad coastline

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

最佳答案

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

解决方法是删除那些长于特定距离的线条,例如500 m.. 首先,找出连续坐标之间的距离大于这个距离的地方:breaks .然后取两个 breaks 之间的坐标子集最后为该子集创建 Lines。您最终会得到一条由多个 ( 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

关于R 从 SpatialPointsDataFrame 到 SpatialLines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22597663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com