Choose one file that has a specific name and the most recently updated

╄→尐↘猪︶ㄣ 提交于 2019-12-24 06:35:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!