问题
I want to choose a file like the following line, which didn't do as I wished.
which(substr(rownames(fInfo),1,8) == "mySource" ) & which.max(fInfo$mtime)
In an English sentence, I want to choose files whose names start with "mySource" and within those whom chosen, I want to pick the most recently updated file.
My script below is suffice, but it is too long. Can someone shorten my script?
# create dummy files under Folder "scriptFld"
ifelse(!dir.exists(file.path("scriptFld")), dir.create(file.path("scriptFld")), FALSE)
strTime = format(Sys.time(), "%H%M")
file.create(NA, paste0("scriptFld/mySource1_", strTime,".R")); Sys.sleep(1)
file.create(NA, paste0("scriptFld/mySource2_", strTime,".R")); Sys.sleep(1)
file.create(NA, paste0("scriptFld/notMySource3_", strTime,".R"))
# read source R files
setwd("scriptFld")
fInfo = file.info(list.files()) # find all files under the folder "scriptFld"
iCandidate = which(substr(rownames(fInfo),1,8) == "mySource") # focus on file names starting with "source"
iCandidateMax = iCandidate[ which.max(fInfo$mtime[iCandidate]) ] # choose the most recent file
fSourceName = rownames(fInfo)[iCandidateMax]
source(file = fSourceName) # This is what I want, except the script is too long.
setwd("..")
(fSourceName)
回答1:
You can do:
library(dplyr)
files <- list.files("scriptFld", pattern = "^mySource", full.names = TRUE)
files %>%
file.info() %>%
pull(mtime) %>%
which.max() %>%
files[.] %>%
source()
来源:https://stackoverflow.com/questions/45875543/choose-one-file-that-has-a-specific-name-and-the-most-recently-updated