在 R 中对文件进行子集化 - 将文件名索引读取为 4 位数字序列,例如0001 到 4000,而不是 1 到 4000)

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

我正在尝试使用 RStudio 从文件夹中提取文件子集,这些文件均使用 4 位数字按顺序命名(例如

Horse0001.jpg
Horse0002.jpg
等)。但是,我遇到了错误,因为我不知道如何让 R 以这种方式读取文件索引 - R 相反尝试将它们视为
Horse1.jpg
Horse2.jpg
等,因此告诉我它可以无法运行该命令,因为它找不到文件
Horse1.jpg
(该文件不存在)。

我知道问题出在代码的

start_index
部分,但我不知道如何操作它。

我希望以上是有道理的。

我的代码如下:

original_dir <- path("data/horsies")
new_base_dir <- path("data/horsies2")
make_subset <- function(subset_name,
                        start_index, end_index) {
  for (category in c("horse", "ponies")) {
    file_name <- glue::glue("{category}.{ start_index:end_index }.png")
    dir_create(new_base_dir / subset_name / category)
    file_copy(original_dir / file_name,
              new_base_dir / subset_name / category / file_name)
  }
}
make_subset("train", start_index = 1, end_index = 2000)
make_subset("validation", start_index = 2001, end_index = 2200)
make_subset("test", start_index = 2201, end_index = 2500)

提前谢谢您!

r rstudio subset
1个回答
0
投票

这应该有效:

file_name <- glue::glue("{category}{ sprintf('%04d', start_index:end_index) }.png")
© www.soinside.com 2019 - 2024. All rights reserved.