【问题标题】:remove rasters with 'NA' values after batch reclassify in R在 R 中批量重新分类后删除具有“NA”值的栅格
【发布时间】:2018-10-17 15:33:26
【问题描述】:

我曾经使用 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 

【问题讨论】:

  • 我会在重新分类和编写栅格之间而不是事后这样做。您可以简单地对栅格进行矢量化并测试 NA 值的长度,例如 length(x[is.na[x]]) == length(x[]) 您的测试条件也可以是单元格的一部分而不是所有 NA .您可以从原始栅格中计算“预期”非 NA 像元的数量。
  • 好的,特别是对于上面的代码,在'#...reclassification'之后但在'#write...'之前的for循环中包含该行,像这样吗?:length(rc[is .na[rc]]) == 长度(rc[])

标签: r list for-loop lapply raster


【解决方案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)
}

【讨论】:

  • 感谢您的意见,它确实切入正题并确保内存安全。
猜你喜欢
  • 1970-01-01
  • 2015-09-27
  • 1970-01-01
  • 1970-01-01
  • 2019-02-04
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 2012-10-30
相关资源
最近更新 更多