使用所需名称字符串编写栅格时出现问题

Problem writing rasters with desired name string

我有大量名称如 "xxxxxxxx2019.01.01" 的目录,然后我想将每个目录名称的所需部分传递给光栅名称 "myRas_..."。然而,光栅名称突然改变,这有时会导致一些被覆盖!

为什么会这样?有人可以帮我解决这个问题吗? 下面是我的脚本的简化版本:

library(raster)
set.seed(1234)

#setting working directory
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))

# create data
r <- raster(nrows = 120, ncol = 120, xmn=0)
r[] <- sample(3, ncell(r), replace=TRUE)

dlist <- "xxxxxxxx2019.01.01"

# Write results myRas_...
raster::writeRaster(r,  
                    file.path(getwd(), paste0("myRas_", stringr::str_sub(dlist,-10,-1), collapse = "")), 
                    format = "GTiff", overwrite=TRUE)

然后输出令人惊讶地保存为myRas_2019.01.tif,而不是myRas_2019_01_01.tif

这可能是由于点 (.) 而发生的,可以通过使用 gsub 或类似的东西替换点来避免。也许其他人可以告诉您一种保留点的方法。

# Write results
raster::writeRaster(r,  
                    file.path(getwd(), paste0("myRas_", gsub("\.", "_", as.character(stringr::str_sub(dlist,-10,-1))))), 
                    format = "GTiff", overwrite=TRUE)