首页 > 解决方案 > 在 R 中批量重新分类后删除具有“NA”值的栅格

问题描述

我曾经使用 for 循环遍历一堆栅格(n = 533),reclassify它们基于将某些值(小于 353.3)转换为“NA”。我现在想要一种有效的方法来搜索重新分类的栅格列表并删除具有所有“NA”值的栅格(请参见下面的输出示例)。如何才能做到这一点?

wfrastlist <- list.files(path = "/path/to/rasters/", 
pattern='*.TIF$', all.files=TRUE, full.names=FALSE)

#generate a reclassification matrix 
#in this example, values less than 353.2 are assigned a new value of 
#'NA' 
m <- c(-Inf, 353.2, NA)
rclmat <- matrix(m, ncol=3, byrow=TRUE)

#function to reclassify rasters and write a new reclassified .tif 
#file for each

batch_reclass <- function(wfrastlist){
  for (i in 1:length(wfrastlist)) {
    #read in raster
    r <-raster(paste0("/path/to/rasters/", wfrastlist[i]))
    #perform the reclassifcation
    rc <- reclassify(r, rclmat)
    #write each reclass to a new file 
    writeRaster(rc, filename = 
    paste0("/path/to/reclassified/rasters/", "rc_", wfrastlist[i]), 
    format="GTiff", overwrite=TRUE)
  }
}
#run the function
batch_reclass(wfrastlist)

#example output
#raster with values within new range
class       : RasterLayer 
dimensions  : 412, 362, 149144  (nrow, ncol, ncell)
resolution  : 20.15372, 20.15372  (x, y)
extent      : 1531426, 1538721, 592978.7, 601282.1  (xmin, xmax, 
ymin, ymax)
coord. ref. : +proj=aea +lat_1=50 +lat_2=58.5 +lat_0=45 +lon_0=-126 
+x_0=1000000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m 
+no_defs 
data source : /path/to/reclassified/rasters/rc_wfrast_basin102.tif 
names       : rc_wfrast_basin102 
values      : 412.6, 424.6  (min, max)

#raster without values within new range (i.e., missing 'values' row)
class       : RasterLayer 
dimensions  : 158, 66, 10428  (nrow, ncol, ncell)
resolution  : 20.15372, 20.15372  (x, y)
extent      : 1551478, 1552809, 602914.5, 606098.8  (xmin, xmax, 
ymin, ymax)
coord. ref. : +proj=aea +lat_1=50 +lat_2=58.5 +lat_0=45 +lon_0=-126 
+x_0=1000000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m 
+no_defs 
data source : /path/to/reclassified/rasters/rc_wfrast_basin103.tif 
names       : rc_wfrast_basin103 

标签: rlistfor-looplapplyraster

解决方案


您可以检查栅格的最小值(或最大值)是否为NA,这意味着只有 NA

rc <- reclassify(r, rclmat)
if (!is.na(minValue(rc))) {
    writeRaster(rc,  paste0("/path/to/reclassified/rasters/", "rc_", wfrastlist[i]), format="GTiff", overwrite=TRUE)
}

推荐阅读