3

我有一组随机段在窗口中(在 spatstat R 中)绘制一种镶嵌(三角形,矩形...... )。我需要将其转换为一组多边形(SpatialPolygons)来计算一些指数(如面积、形状指数......)。

这显然很简单,但我找不到如何去做......

这是Carl Witthoft的一段代码,它生成了一个随机模式的自截断段:

ranpoly <- function(numsegs=10,plotit=TRUE) {

require(spatstat)
# temp fix: put the first seg into segset. Later make it a constrained random.
segset<-psp(c(0,1,1,0,.25),c(0,0,1,1,0),c(1,1,0,0,1),c(0,1,1,0,.75),owin(c(0,1),c(0,1)) ) #frame the frame
for (jj in 1: numsegs) {
# randomly select a segment to start from, a point on the seg, the slope,and direction
# later... watch for slopes that immediately exit the frame
endx <-sample(c(-0.2,1.2),1)  #force 'x1' outside the frame
# watch that sample() gotcha
if(segset$n<=5) sampset <- c(5,5) else sampset<-5:segset$n
startseg<-sample(sampset,1) #don't select a frame segment
# this is slope of segment to be constructed
slope <- tan(runif(1)*2*pi-pi) # range +/- Inf 
# get length of selected segment
seglen<-lengths.psp(segset)[startseg]
startcut <- runif(1) 
# grab the coords of starting point (similar triangles)
startx<- segset$ends$x0[startseg] + (segset$ends$x1[startseg]-segset$ends$x0[startseg])*startcut #seglen
starty<- segset$ends$y0[startseg] + (segset$ends$y1[startseg]-segset$ends$y0[startseg])*startcut #seglen
# make a psp object with that startpoint and slope; will adjust it after finding intersections
endy <- starty + slope*(endx-startx)
newpsp<-psp(startx,starty,endx,endy,segset$window,check=FALSE)
# don't calc crossing for current element of segset
hits <- crossing.psp(segset[-startseg],newpsp)
segdist <- dist(cbind(c(startx,hits$x),c(starty,hits$y)))
# dig back to get the crosspoint desired -- have to get matrixlike object out of class "dist" object
# And, as.matrix puts a zero in location 1,1 kill that row.
cutx <- hits$x[ which.min( as.matrix(segdist)[-1,1] )]
cuty <- hits$y[which.min(as.matrix(segdist)[-1,1] )]
segset <- superimpose(segset,psp(startx,starty,cutx,cuty,segset$window))

} #end jj loop
if(plotit) plot(segset,col=rainbow(numsegs))
return(invisible(segset))
}

segset=ranpoly()

segset 是我需要创建 SpatialPolygons 对象的 psp 对象。

4

2 回答 2

1

谷歌搜索让spatstat as spatialPolygons我找到了第一个命中,这是 spatstat 中专门用于处理 shapefile 的小插图。它在如何将sp-classes 转换为 spatstat 对象上花费了大量时间。您可能对第 3.2.5 节:SpatialPolygons 类的对象和第 3.2.6 节:SpatialPolygonsDataFrame类的对象最感兴趣。

于 2013-01-28T13:05:17.087 回答
1

假设您有一组 spatstat 对象,您可以尝试类似(未经测试):

require(sp)

# VECTOR OF spatstat OBJECT NAMES
segs <- (seg1,seg2,seg3)

segPolys <- as(segs[1], "SpatialPolygons")
  for( i in 2:length(segs)) {
    y <- as(segs[i], "SpatialPolygons")
      slot(y[[i]], "ID") <- paste(i)
    segPolys <- c(slot(y, "polygons"),segPolys)
   }
于 2013-01-28T17:52:18.383 回答