the below code finds the most recently modified file within a folder. Can anyone advise please how this can be amended to instead find the penultimate/second to last file that was modified? Can the which.max be amended to search for a -1 or is alternative code required?
#Open latest file
#get a vector of all filenames
files <- list.files(path="MYFILEPATH",pattern="files.xls",full.names = TRUE,recursive = TRUE)
#get the directory names of these (for grouping)
dirs <- dirname(files)
#find the last file in each directory (i.e. latest modified time)
lastfiles <- tapply(files,dirs,function(v) v[which.max(file.mtime(v))])
File_List <- file.info(list.files("//MYFILEPATH", full.names = T))
Path_Of_Interest <- rownames(File_List)[which.max(File_List$mtime)]
CodePudding user response:
Split the files by directory, then loop, order and get the 2nd from the last:
lapply(split(files, dirname(files)), function(i){
i[ order(file.mtime(i)) ][ length(i) - 1 ]
})
CodePudding user response:
Something like this?
Instead of getting the entire file.info
, the code below calls file.mtime
.
Tested with files in a sub-directory of my home dir.
# my tmp dir
MYFILEPATH <- "~/tmp"
# get a vector of all filenames
files <- list.files(
path=MYFILEPATH,
pattern="\\.txt$",
full.names = TRUE,
recursive = TRUE
)
File_mtime <- file.mtime(files)
i <- order(File_mtime, decreasing = TRUE)
Second_Path <- if(length(i) > 1L) files[ i[2L] ] else files
Second_Path
The code above as a function.
The default is to return the last file changed. Argument default n = 1
must set to n = 2
for the function to return the before-last file changed.
nth_from_last_changed <- function(path = ".", pattern = NULL, n = 1L,
full.names = TRUE, recursive = TRUE, ...){
#get a vector of all filenames
files <- list.files(
path = path,
pattern = pattern,
full.names = full.names,
recursive = recursive,
...
)
# get their last change time and order decreasing
i <- order(file.mtime(files), decreasing = TRUE)
if(length(i) > n - 1L)
files[ i[n] ]
else files[length(i)]
}
nth_from_last_changed("~/tmp", "\\.txt", n = 2)