【问题标题】:Crop multiple Rasters (ASCII)裁剪多个栅格 (ASCII)
【发布时间】:2019-01-06 12:22:51
【问题描述】:

我需要裁剪 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(...)`

【问题讨论】:

  • 谢谢你,米奇。但不是真的。我无法解决这个问题。我有我需要裁剪的 ASCII 栅格列表(“files2”),并且我有一个掩码来裁剪这些栅格(“mask_raster”)。我想需要一个循环来遍历光栅,剪切它们,将其导出到具有原始文件名称的文件夹中,然后重复。对吗?
  • 你有没有想出可以裁剪单个栅格的代码?在担心如何跨多个栅格运行此代码之前,请专注于开发代码来执行此操作。如果您确实编写了一些代码来裁剪单个栅格,则应将其添加到问题中。希望我今天晚些时候有时间正确回答这个问题,但这些细节应该更容易解决:)
  • 我在网上找到了可以根据需要进行更改的内容。它使用 shapefile 来切出光栅。由于我没有让它与光栅一起使用,我将光栅掩码文件转换为 shapefile。如果有兴趣,您可以在这里找到代码:r-sig-geo.2731867.n2.nabble.com/…Furter down,作者 Mauricio。无论如何,谢谢米奇
  • 为了完成,最好发布您对问题的解决方案,以防其他人遇到同样的问题:)

标签: r raster


【解决方案1】:

我没有找到一个简单的解决方案来通过一个栅格裁剪多个栅格,而是通过一个形状文件。所以我只是回到 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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2016-07-29
    • 2021-11-20
    • 2017-05-22
    相关资源
    最近更新 更多