如何重命名 R 中不同子文件夹中的多个文件,同时将它们保留在原始文件夹中

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

'''

fieldszn <- '~/Desktop/hls project/fieldszn'
bands <- list.files(fieldszn, pattern = "*.tiff", recursive = TRUE, full.names = FALSE)
new_names <- c("red", "nir", "fmask")
file.rename(bands, paste0(new_names,"*.tiff"))

ndvi <- function(path, nir_band = nir, red_band = red){
  img <- stack(path)
  nir <- img[[nir_band]]
  red <- img[[red_band]]
  vi <- ((nir-red)/(nir+red))
  
  terra::writeRaster(vi, file.path(bg21, paste(tools::file_path_sans_ext(basename(path)), '_ndvi.tiff', sep = "")))
}

lapply(bands_bg21, ndvi)

'''

我目前有 9 个不同的子文件夹,每个子文件夹有 3 个光栅波段,用于呈现单个图像(所有这些都采用资产链接的格式,包括颗粒 ID、卫星类型等)。我正在尝试迭代它们以重命名为常见名称,例如 red、nir 和 fmask,这样我就可以迭代它们以运行植被指数计算。我已经能够重命名它们,但它们最终会进入工作目录而不是原始文件夹,而且我还没有弄清楚如何在不添加数字的情况下迭代它们。

重命名文件后,我计划通过植被指数计算来迭代它们 - 但我不确定如何设置它。

请帮忙!我是 R 新手,希望得到任何帮助。

visual of the raster band structure

current file structure

the issue of automated save in directory

r loops subdirectory file-rename
1个回答
0
投票

我认为问题在于新文件名中没有包含文件夹路径,因此 file.rename 默认将文件移动到您的工作目录。

您可以使用

file.path()
组合路径和文件名。

new_names <- file.path(fieldszn, paste0(c("red", "nir", "fmask"), ".tiff"))
file.rename(bands, new_names)
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.