在R中重新分类后,删除具有“ NA”值的栅格

时间:2018-10-17 15:33:27

标签: r list for-loop lapply raster

我曾经使用for循环迭代一堆栅格(n = 533),并根据将某些值(小于353.3)转换为“ NA”来reclassify对其进行迭代。现在,我希望有一种有效的方法来搜索重新分类的栅格列表,并删除具有所有“ 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 

1 个答案:

答案 0 :(得分:1)

将来,请提供一个可复制的示例。 您可以检查栅格的最小值(或最大值)是否为NA,这意味着仅存在NAs

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