创建一个循环,遍历文件中的多个栅格并执行 QC

问题描述 投票:0回答:1

我创建了从文件夹下载各个 hdf 文件的代码,将它们转换为栅格,然后使用 QC 栅格删除 NDVI 和 EVI 图层中的像素。

但是,我在同一个文件夹中有大约 4 个单独的文件,时间跨度为 1 个月。我可能会下载跨越一年的文件,这将是相当多的文件。

我的问题是,是否可以创建一个循环来遍历所有单独的文件,删除每个文件中不必要的层,最后进行质量控制?然后,我可以创建该文件夹中所有文件的堆栈。

我的单个文件的代码如下:

t <- rast("MYD13Q1.A2020313.h16v07.061.2020353215522.hdf")
names(t) #Check levels
ndvi_1 <- t[[1]] #Create raster with just ndvi
evi_1 <- t[[2]] #Create raster with just evi
qc_1 <- t[[12]] #Create raster with just qc
date_1 <- t[[11]] #Create raster with just date

plot(qc_1) #Check qc raster
qc_1[qc_1 > 1] <- NA #Remove pixels with a score of more than 1 as these are classed as bad pixels
ndvi_1_qc <- mask(ndvi_1, qc_1) #Remove pixels from ndvi by masking with qc raster
evi_1_qc <- mask(ndvi_1, qc_1) #Remove pixels from evi by masking with qc raster
plot(ndvi_1_qc)
stack1 <- (ndvi_1_qc, evi_1_qc, date_1) #Create raster stack 
r loops geospatial terra
1个回答
0
投票

我想你的文件夹中只有 hdf 文件。

library(terra)
applyQC <- function(path){
  
  t <- terra::rast(path)
  ndvi_1 <- t[[1]] #Create raster with just ndvi
  evi_1 <- t[[2]] #Create raster with just evi
  qc_1 <- t[[12]] #Create raster with just qc
  date_1 <- t[[11]] #Create raster with just date
  
  plot(qc_1) #Check qc raster
  qc_1[qc_1 > 1] <- NA #Remove pixels with a score of more than 1 as these are classed as bad pixels
  ndvi_1_qc <- terra::mask(ndvi_1, qc_1) #Remove pixels from ndvi by masking with qc raster
  evi_1_qc <- terra::mask(ndvi_1, qc_1) #Remove pixels from evi by masking with qc raster
  stack1 <- c(ndvi_1_qc, evi_1_qc, date_1) 
  return(stack1)
}

my_files <- list.files(path = "path/to/files",full.names = T)
stack_list <- lapply(my_files, applyQC)
stacks <- do.call(c,stack_list)

这个想法是将代码包装到一个函数中,然后

lapply
覆盖文件夹内的文件路径。我想所有 .hdf 文件在结构、图层名称、CRS、分辨率等方面都是相同的。

© www.soinside.com 2019 - 2024. All rights reserved.