-->

选择一个文件,有一个特定的名字和最近更新(Choose one file that has a sp

2019-09-29 02:19发布

我需要选择一个类似于下面的行,因为我希望它没有做的文件。

which(substr(rownames(fInfo),1,8) == "mySource" ) & which.max(fInfo$mtime)

在一个英语句子,我想选择的文件的名字开始与“MYSOURCE”并在那些被选择,我要挑最近更新的文件。

我下面的脚本是不够的,但是实在是太长了。 有人可以缩短我的脚本?

# 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)

Answer 1:

你可以做:

library(dplyr)
files <- list.files("scriptFld", pattern = "^mySource", full.names = TRUE)
files %>%
  file.info() %>%
  pull(mtime) %>%
  which.max() %>%
  files[.] %>%
  source()


文章来源: Choose one file that has a specific name and the most recently updated
标签: r which