首页 > 解决方案 > R脚本:识别目录中满足条件的最新文件

问题描述

我想读取文件名为abcd_all_XXX_9999.xlsx 的最新文件,其中XXX代表TETKEKKTET,而 9999 代表循环鼓手(4 位数字)。选择时间段(例如 2015-2025)并在数据处理(合并)后,将文件保存到一个名为CCC1_9999_y的新文件中,其中 y 代表 a 或 b 或 c 或 d 或 e,由我在管理中选择的脚本。 总结

非常感谢您提前!

标签: r

解决方案


这是您问题的通用方法。如果您有任何问题将其转化为您的情况,请告诉我。为了演示,我制作了三个 .csv 文件,每个文件都在我的工作目录中创建了几秒钟"./test"

我们可以使用list.files(). 在您的情况下,您将需要像这样使用模式匹配list.files(pattern = "abcd_all_", ...)

将其包装起来file.info(),我们可以检索有关由list.files(). mtime在我的示例中,我正在获取(参见参考资料)的最小(最新)值?file.info()

然后很容易读取第二个数据集,合并并将结果写入文件。

注意我使用 .csv 文件是因为它们更易于使用。readxl::read_xlsx()如果您将继续使用 .xlsx,您可能会想要使用。

演示:

list.files(path = "./test")
#> [1] "iris.csv"  "iris2.csv" "iris3.csv"

df <- file.info(list.files(pattern = "iris", path = "./test", full.names = TRUE))
df
#>                  size isdir mode               mtime               ctime
#> ./test/iris.csv  4972 FALSE  666 2021-10-12 08:33:55 2021-10-12 08:33:17
#> ./test/iris2.csv 4972 FALSE  666 2021-10-12 08:36:43 2021-10-12 08:36:43
#> ./test/iris3.csv 4972 FALSE  666 2021-10-12 08:35:31 2021-10-12 08:35:31
#>                                atime exe
#> ./test/iris.csv  2021-10-12 08:37:15  no
#> ./test/iris2.csv 2021-10-12 08:37:15  no
#> ./test/iris3.csv 2021-10-12 08:37:15  no

newestfile <- rownames(df[df$mtime == min(df$mtime),])
newestfile
#> [1] "./test/iris.csv"

output <- merge(read.csv(newestfile), otherfile, ...)

write.csv(output, ...)

您的数据(未经测试):

y <- "a"
vars <- c("TET", "KEK", "KTET")
years <- 2015:2025

for(v in vars){
  for(year in years){
  
    df <- file.info(list.files(
      pattern = paste0("abcd_all_", v, "_", year),
      path = ".",
      full.names = TRUE))
    
    newestfile <- rownames(df[df$mtime == min(df$mtime),])
    
    leftside <- readxl::read_xlsx(newestfile)
    
    rightside <- readxl::read_xlsx(paste0("CCC1_", year, "_", y, ".xlsx"))
    
    # all=FALSE specifies "inner-join"
    output <- merge(leftside, rightside, by = "ID", all = FALSE)
    
    write.csv(output, paste0("CC1_", year, "_", y, ".csv"))
  }
}

推荐阅读