R:在投影坐标系上创建协变量

时间:2017-05-24 22:38:54

标签: r pixel coordinate-systems spatstat

我正在尝试使用Spatstat包创建一个协变量,我有一个shp文件作为多边形,以便如果点位于多边形之外,则为协变量指定一个值。我的问题是坐标投影有问题,因为当我完成这个过程时,我有一个奇怪的人物,有人可以帮助我。我的代码:

#Creating covariate Z:

W<- owin(xrange=c(767768.3,768773.6),yrange=c(517335.8,518044.8))
xp<-c(768773.6) #cambia!
yp<-c(518044.8)
X<-ppp(x=xp,y=yp,W)
par(mfrow=c(2,2))
Z<-density(X,500)/(7e-06)

#reading and projecting the shp:

Prodes1<-readOGR(dsn="forestsseparate.shp", layer="forestsseparate", dropNULLGeometries=TRUE)
projection(Prodes1)<-CRS("+proj=utm +zone=18 +ellps=intl +towgs84=307,304,-318,0,0,0,0 +units=m +no_defs")

#Extracting the shp polygon coordinates:

xcoords<-rev(Prodes1@polygons[[1]]@Polygons[[1]]@coords[,1])
ycoords<-rev(Prodes1@polygons[[1]]@Polygons[[1]]@coords[,2])
pruebalu<-owin(poly=list(x=xcoords,y=ycoords))

mx<-(Z$xrange[2]-Z$xrange[1])/Z$xstep
my<-(Z$yrange[2]-Z$yrange[1])/Z$ystep

xcoorde<-matrix(NA,nrow=1,ncol=mx)
ycoorde<-matrix(NA,nrow=1,ncol=my)

#Finding each pixel center

for(i in 1:mx){
  xcoorde[i]<-(Z$xrange[1]+i*Z$xstep) -Z$xstep/2
}

for(i in 1:my){
  ycoorde[i]<-(Z$yrange[1]+i*Z$ystep) -Z$ystep/2
}

#Changing the pixel value if is outside the polygon:

for(i in 1:length(Z$xcol)){
    for(j in 1: length(Z$yrow)){

        if(inside.owin(xcoorde[i],ycoorde[j], pruebalu)==FALSE){
            whichPixel<-nearest.raster.point(xcoorde[i], ycoorde[j], Z)
            Z$v[whichPixel$col,whichPixel$row]<-0.4
        }
    }
}

这是我的结果:

enter image description here enter image description here enter image description here

1 个答案:

答案 0 :(得分:0)

抱歉,我对Z $ v元素的顺序犯了一个错误,这是更正:

for(i in 1:length(Z$xcol)){
    for(j in 1: length(Z$yrow)){

        if(inside.owin(xcoorde[i],ycoorde[j], pruebalu)==FALSE){
            whichPixel<-nearest.raster.point(xcoorde[i], ycoorde[j], Z)
            Z$v[whichPixel$row,whichPixel$col]<-0.4
        }
    }
}

现在很完美!