如何在R中为HDF文件编写循环?

时间:2015-06-04 23:05:25

标签: r mosaic hdf

我在一个文件夹中有超过1,000张MODIS HDF图像:

M:\join

他们的名字告诉我们哪些HDF文件属于某个特定日期,必须拼凑在一起。

例如,在下面, 2009090 表示这三张图片属于同一日期,必须拼接在一起:

MOD05_L2.A2009090.0420.051.2010336084010
MOD05_L2.A2009090.0555.051.2010336100338
MOD05_L2.A2009090.0600.051.2010336100514

或者这两个是同一天, 2009091

MOD05_L2.A2009091.0555.051.2010336162871
MOD05_L2.A2009091.0600.051.2010336842395

现在,我能够成功使用mosaicHDF()将它们镶嵌一个日期,如下所示:

hdfs <- c('MOD05_L2.A2009090.0420.051.2010336084010.hdf',
          'MOD05_L2.A2009090.0555.051.2010336100338.hdf',
          'MOD05_L2.A2009090.0600.051.2010336100514.hdf')

mosaicHDF(hdfNames=hdfs, filename='newhdf.hdf', MRTpath='C:/MRT/bin',bands_subset="1 0 0 0", delete=FALSE) 

由于文件夹中有1年以上的1000多个HDF文件,我应该如何为所有HDF文件编写循环使用此类函数,并为每个日期制作马赛克文件?

如果有人能帮助我,我将非常感激。

感谢。

2 个答案:

答案 0 :(得分:2)

使用grep按ID分组文件,然后使用for循环为每个组创建镶嵌:

fnames <- c("MOD05_L2.A2009090.0420.051.2010336084010", "MOD05_L2.A2009090.0555.051.2010336100338", "MOD05_L2.A2009090.0600.051.2010336100514", "MOD05_L2.A2009091.0555.051.2010336162871", "MOD05_L2.A2009091.0600.051.2010336842395")
#or
fnames <- list.files(path = "M:/join/", pattern = "*.hdf") #Credits do @Gregor for noticing this

ids <- unique(substr(fnames, 10, 17))

groups <- sapply(ids, grep, fnames, value=TRUE)

for (gr in seq_along(groups)) {
  mosaicHDF(hdfNames=groups[[gr]], filename=paste0(names(groups)[gr], '.hdf'), 
            MRTpath='C:/MRT/bin',bands_subset="1 0 0 0", delete=FALSE)
}

这应保存每个组的所有马赛克文件,文件名为组ID。

答案 1 :(得分:0)

    fnames <- c("MOD05_L2.A2009090.0420.051.2010336084010", "MOD05_L2.A2009090.0555.051.2010336100338", "MOD05_L2.A2009090.0600.051.2010336100514", "MOD05_L2.A2009091.0555.051.2010336162871", "MOD05_L2.A2009091.0600.051.2010336842395")
    #or
    fnames <- list.files(path = "M:/join/", pattern = "*.hdf") #Credits do @Gregor for noticing this

    ids <- unique(substr(fnames, 10, 17))

    groups <- lapply(ids, grep, fnames, value=TRUE)  # This line should be lapply instead of sapply
    ref.num = substr(groups[[j]][1], 10, 17) #Give output different names


for (gr in seq_along(groups)) {
ref.num = substr(groups[[gr]][1], 10, 17) 
      mosaicHDF(hdfNames=groups[[gr]], filename=paste0("MOD05_",ref.num, ".hdf"), 
                MRTpath='C:/MRT/bin',bands_subset="1 0 0 0", delete=FALSE)
    }