r - R脚本:识别目录中满足条件的最新文件
问题描述
我想读取文件名为abcd_all_XXX_9999.xlsx 的最新文件,其中XXX代表TET或KEK或KTET,而 9999 代表循环鼓手(4 位数字)。选择时间段(例如 2015-2025)并在数据处理(合并)后,将文件保存到一个名为CCC1_9999_y的新文件中,其中 y 代表 a 或 b 或 c 或 d 或 e,由我在管理中选择的脚本。 总结:
- 确定满足条件的最新文件:abcd_all_XXX_9999.xlsx,其中 abcd_all_ 是固定的。
- 读取第二个数据集(第二个数据集的名称可以是任何名称)
- 按 ID 合并(一对一)两个数据帧。保存名为 CCC1_9999_y 的合并数据集文件,其中 y 代表 a 或 b 或 c 或 d 或 e,由我在脚本管理中选择。9999 对应于与 abcd_all_XXX_9999.xlsx 相同的循环编号。
非常感谢您提前!
解决方案
这是您问题的通用方法。如果您有任何问题将其转化为您的情况,请告诉我。为了演示,我制作了三个 .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"))
}
}
推荐阅读
- django - Django 创建动态表单,查询集的值作为字段
- html - Bootstrap3:定义固定宽度的列,连续超过 12 列
- angular - 访问模板中组件的对象属性不会显示该对象的属性
- javascript - 如何使用 vanilla javascript 将 html 表中的数据转换为对象数组
- java - 如何将地图列表转换为xml
- docker - 在 Docker 环境中实现 Consul 健康检查
- javascript - chrome 和 firefox 中新标签的 Blob 名称问题
- ios - 如果从 Siri 快捷方式执行操作,我应该捐赠交互吗?
- c - 在 C 中打印图形的替代方法
- python - Python 3:无法将二进制数据转换为文本