line - R from SpatialPointsDataFrame to SpatialLines -
i'have spatialpointsdataframe load
pst<-readogr("/data_spatial/coast/","points_coast")
and spatiallines in output, have find somthing
coord<-as.data.frame(coordinates(pst)) slo1<-line(coord) sli1<-lines(list(slo1),id="coastline") coastline <- spatiallines(list(sli1)) class(coastline)
it seems work when try plot(coastline) , have line should not there ...
some 1 can me ? the shapefile here !
i have looked @ shapefile. there id
column, if plot data, seems id not ordered north-south or something. lines created because point order not perfect, connecting points next each other in table, far each other in terms of space. try figure out correct ordering of data calculating distances between points , ordering on distance.
a workaround remove lines longer distance, e.g. 500 m.. first, find out distance between consecutive coordinates larger distance: breaks
. take subset of coordinates between 2 breaks
, lastly create lines subset. end coastline consisting of several (breaks-1
) segments , without erroneous ones.
# 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 , 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 , check breaks plot(coord,type='n') points(coord[breaks,], pch=16,cex=1) # create vector filled lines of each subset ll <- vector("list", length(breaks)-1) (i in 1: (length(breaks)-1)){ subcoord = coord[(breaks[i]+1):(breaks[i+1]),] # check if subset contains more 2 coordinates if (nrow(subcoord) >= 2){ slo1<-line(subcoord) sli1<-lines(list(slo1),id=paste0('section',i)) ll[[i]] = sli1 } } # remove invalid lines nulls = which(unlist(lapply(ll,is.null))) ll = ll[-nulls] lin = spatiallines(ll) # add result 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')
Comments
Post a Comment