简体   繁体   English

在 R 中循环指定文件名(converting.nc to geotiff)

[英]Specifying file names in a loop in R (converting .nc to geotiff)

I have a folder of.nc files on sea surface temperature, and I have a loop which extracts the variable I want ("analysed_sst") from the.nc file and writes the files to rasters.我有一个关于海面温度的 .nc 文件文件夹,我有一个循环,它从 .nc 文件中提取我想要的变量(“analysed_sst”)并将文件写入栅格。 I want to specify the name of the outputted raster files to be the first section of the original.nc file (which is the date).我想将输出的光栅文件的名称指定为 original.nc 文件的第一部分(即日期)。

An example would be that the original.nc file is called "20220113090000-JPL-L4_GHRSST-SSTfnd-MUR25-GLOB-v02.0-fv04.2.nc" and so I would like the outputted raster to be called "20220113_STT.tiff".一个例子是 original.nc 文件被称为“20220113090000-JPL-L4_GHRSST-SSTfnd-MUR25-GLOB-v02.0-fv04.2.nc”,所以我希望输出的光栅被称为“20220113_STT.tiff ”。 I've attached the loop I'm using below.我在下面附上了我正在使用的循环。

library(ncdf4)
library(raster)
   
#input directory
dir.nc <- #file path

files.nc <- list.files(dir.nc, full.names = T, recursive = T)

#output directory
dir.output <- #file path

#loop 
for (i in 1:length(files.nc)) {
  r.nc <- raster(files.nc[i])
  writeRaster(r.nc, paste(dir.output, i, '.tiff', sep = ''), format = 'GTiff', overwrite = T)
}

dirname() is vectorized so you should be able to safely use dirname(files.nc) to get the directory for each file. dirname()是矢量化的,因此您应该能够安全地使用dirname(files.nc)来获取每个文件的目录。

Side note: It can be safer to use seq_along(files.nc) rather than 1:length(files.nc) .旁注:使用seq_along(files.nc)而不是1:length(files.nc)会更安全。 When length(files.nc) == 0 you can get some confusing errors because 1:0 produces [1] 1 0 and your loop will try to do some weird stuff.length(files.nc) == 0你会得到一些令人困惑的错误,因为1:0产生[1] 1 0并且你的循环将尝试做一些奇怪的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM