有没有办法在R中写一个for循环来批量转换tif到asc文件?

z3yyvxxp  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(143)

我想在R中创建一个循环来自动选择文件并将其转换为不同的文件类型(.tif到.asc)。我不想手动选择每个文件,是否有方法在R中做到这一点?
这就是我一直在手动做的事情,但它很慢而且乏味。

bioclim19<-file.choose()

bioclim19asc<-raster(bioclim19)
bioclim19asc<-aggregate(bioclim19asc,fact=2)

writeRaster(bioclim19asc,"bioclim19.asc",format="ascii")
s4n0splo

s4n0splo1#

正如IRFTM所建议的,下面的代码可能符合您的要求..让我知道这是否有帮助..

# directory address where your files are
setwd("path/to/directory")

# list of all (and only) .tif files in that directory
tif_files <- list.files(pattern = "\\.tif$")

# loop through each file and convert to .asc format
for (f in tif_files) {
  # read in the raster object
  rasterObject <- raster(f)
  
  # aggregate the raster object
  aggRaster <- aggregate(rasterObject, fact = 2)
  
  # write aggregated raster object into a .asc file
  writeRaster(aggRaster, file.path(filePath_toSave_File, 
               gsub("\\.tif$", ".asc", file)), format = "ascii")
}

相关问题