我需要裁剪50多个光栅文件(ASCII格式)。我已经也以ASCII格式从ArcMap导出了蒙版并将其加载到R中。如何使它适用于一行中的所有栅格,并使用与以前相同的名称导出它们(当然,在不覆盖的其他文件夹中) ?
我知道raster包中有一个裁剪功能,但到目前为止我从未使用过。我只将它们堆叠起来以进行进一步的栖息地分析。
到目前为止,我的代码:
#### Use only part of area
files2 <- list.files(path="D:/",full.names=TRUE, pattern = "\\.asc$")
files2
# Create a RasterLayer from first file
mask_raster <- raster(files2[1])
# Crop. But how??
crop(x = , y=mask_raster)
writeRaster(...)`
答案 0 :(得分:0)
我没有找到一种简单的解决方案来通过栅格来裁剪多个栅格,而是通过形状文件进行裁剪。所以我只是回到ArcMap并将栅格转换为shapefile。然后在R中,裁剪和遮罩是关键步骤。参见下面的代码(从Mauricio Zambrano-Bigiarini的代码修改而来)。希望这会有所帮助。
# Reading the shapefile (mask to crop later)
Maskshp <- readOGR("mask.shp")
# Getting the spatial extent of the shapefile
e <- extent(Maskshp)
# for loop with (in this case) 60 runs
for (i in 1:60) {
# Reading the raster to crop
files <- list.files(path="...your path",full.names=TRUE, pattern = "\\.asc$")
Env_raster <- raster(files[i])
# Save the filename
filename <- (paste(basename(files[i]), sep=""))
# Crop the raster
Env_raster.crop <- crop(Env_raster, e, snap="out")
# Dummy raster with a spatial extension equal to the cropped raster,
# but full of NA values
crop <- setValues(Env_raster.crop, NA)
# Rasterize the catchment boundaries, with NA outside the catchment boundaries
Maskshp.r <- rasterize(Maskshp, crop)
# Putting NA values in all the raster cells outside the shapefile boundaries
Maskshp.masked <- mask(x=Env_raster.crop, mask=Maskshp.r)
plot(Maskshp.masked)
#Export file to working directory with original name as new name
writeRaster(Maskshp.masked, filename)
}