【发布时间】:2018-01-20 11:49:57
【问题描述】:
我想裁剪高程栅格以将其添加到栅格堆栈。这很容易,我之前很顺利地做到了这一点,将生态区域栅格添加到同一个堆栈中。但是对于海拔一号,它是行不通的。现在,这里有几个问题在溢出解决这个问题,我尝试了很多东西......
首先,我们需要这个:
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 海拔
我尝试了相反的方法...使 predictors2 范围满足海拔的范围...也没有。
但后来我读到了
您可能不想使用 setExtent() 或 extent()
并且我试图通过这样做来获得我的栅格的最小公共范围,遵循@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)
【问题讨论】:
-
要写入光栅堆栈,删除
options="INTERLEAVE=BAND"并使用bylayer = F -
@aldo_tapia,感谢您的提示,bylayer = F 完全有意义!