在 R 中获取最新文件 - Rstudio

Get most current file in R - Rstudio

我用的是R,目前需要进入电脑的一个文件夹,那个文件夹里面还有其他文件夹,每个文件夹里面有很多excel个文件,我需要获取最新的每个文件夹。

文件夹结构:

C: \ book \

C: \ book \ x
C: \ book \ x \ x.xlsx
C: \ book \ x \ xx.xlsx
C: \ book \ x \ xxx.xlsx

C: \ book \ y
...
C: \ book \ z
...

有什么办法可以优化吗?

这主要是 or Read multiple CSV files into separate data frames 之一的骗局。对于后者,我反对将帧存储在 list 个帧中而不是单个文件中的建议,但是......这是上下文相关的,可能不适合您的特定用途。

无论如何,这里有一个包含“最新文件”的改编:

LF <- list.files(path = "path/to", recursive = TRUE, full.names = TRUE)
recent_LF <- c(by(LF, dirname(LF), function(filenames) {
  filenames[ which.max(file.info(filenames)[,"mtime"]) ]
}))

编辑: 有时我认为 list.files 应该默认为:

list.files <- function(path, ..., recursive = FALSE, full.names = recursive, ...) {
  # ...
}

我认为 recursive=TRUE, full.names=FALSE 没有任何价值,这就是这个答案的第一个版本所发生的情况。