2017-05-24 37 views
0

我想用包Spatstat创建协变量,如果点在多边形之外,我有一个shp文件作为多边形以便为协变量赋值。我的问题是在坐标投影上存在问题,因为当我完成这个过程时,我有一个奇怪的数字,请有人帮助我。我的代码:R:在投影坐标系上创建一个协变量

#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([email protected][[1]]@Polygons[[1]]@coords[,1]) 
ycoords<-rev([email protected][[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 hereenter image description hereenter image description here

回答

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 
     } 
    } 
} 

现在完美!