我想裁剪高程栅格以将其添加到栅格堆栈中。这很容易,我之前很顺利地做到了这一点,将生态区域栅格添加到同一个堆栈中。但是对于海拔一号,它是行不通的。现在,这里有几个问题溢出来解决这个问题,我尝试了很多东西......
首先,我们需要这个:
library(rgdal)
library(raster)
我的堆栈是 predictors2:
#Downloading the stack
predictors2_full<-getData('worldclim', var='bio', res=10)
#Cropping it, I don' need the whole world
xmin=-120; xmax=-35; ymin=-60; ymax=35
limits <- c(xmin, xmax, ymin, ymax)
predictors2 <- crop(predictors2_full,limits)
然后我在这里下载了 terr_ecorregions shapefile:http: //maps.tnc.org/files/shp/terr-ecoregions-TNC.zip
setwd("~/ORCHIDACEAE/Ecologicos/w2/layers/terr-ecoregions-TNC")
ecoreg = readOGR("tnc_terr_ecoregions.shp") # I've loaded...
ecoreg2 <- crop(ecoreg,extent(predictors2)) # cropped...
ecoreg2 <- rasterize(ecoreg2, predictors2) # made the shapefile a raster
predictors4<-addLayer(predictors2,elevation,ecoreg2) # and added the raster
# to my stack
有了海拔,我就是做不到。数字高程模型基于 GMTED2010,可在此处下载:http: //edcintl.cr.usgs.gov/downloads/sciweb1/shared/topo/downloads/GMTED/Grid_ZipFiles/mn30_grd.zip
elevation<-raster("w001001.adf") #I've loaded
elevation<-crop(elevation,predictors2) # and cropped
但是海拔的范围与 predictors2 的范围略有不同:
> extent(elevation)
class : Extent
xmin : -120.0001
xmax : -35.00014
ymin : -60.00014
ymax : 34.99986
>
我试图通过我在此处的问题中读到的一切手段使 then 相等...我尝试扩展,因此海拔的 ymax 将满足 predictors2 的 ymax 海拔<-extend(elevation,predictors2) #没有用,范围保持不变
我尝试了相反的方法……使 predictors2 范围满足海拔的范围……也没有。
但后来我读到了
您可能不想使用 setExtent() 或 extent() <- extent(),因为您可能以错误的栅格地理坐标结束 - @ztl,2015 年 6 月 29 日
我试图通过这样做来获得我的栅格的最小共同范围,遵循@zlt 在另一个范围问题中的回答
# Summing your rasters will only work where they are not NA
r123 = r1+r2+r3 # r123 has the minimal common extent
r1 = crop(r1, r123) # crop to that minimal extent
r2 = crop(r2, r123)
r3 = crop(r3, r123)
为此,首先我必须设置分辨率:
res(elevation)<-res(predictors2) #fixing the resolutions... This one worked.
但后来,r123 = r1+r2+r
没有工作:
> r123=elevation+ecoreg2+predictors2
Error in elevation + ecoreg2 : first Raster object has no values
任何人都可以给我一个提示吗?我真的很想将我的高程添加到栅格中。有趣的是,我有另一个名为 predictors1 的堆栈,其高度范围完全相同......而且我能够裁剪 ecoreg 并将 ecoreg 添加到 predictors1 和 predictors2... 为什么我不能对海拔做同样的事情?我对这个世界很陌生,没有想法……我很感激任何提示。
编辑:解决方案,感谢@Val
我得到了这个:
#Getting the factor to aggregate (rasters are multiples of each other)
res(ecoreg2)/res(elevation)
[1] 20 20 #The factor is 20
elevation2<-aggregate(elevation, fact=20)
elevation2 <- crop(elevation2,extent(predictors2))
#Finally adding the layer:
predictors2_eco<-addLayer(predictors2,elevation2,ecoreg)
新问题,想...
我无法将堆栈写入 geotiff
writeRaster(predictors2_eco, filename="cropped_predictors2_eco.tif", options="INTERLEAVE=BAND", overwrite=TRUE)
Error in .checkLevels(levs[[j]], value[[j]]) :
new raster attributes (factor values) should be in a data.frame (inside a list)