2017-08-25 72 views
0

我想选择一个像下面这行那样的文件,但没有按照我的意愿去做。R:选择一个具有特定名称和最近更新的文件

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) 
+2

怎么样'X < - list.files(模式= “^ MYSOURCE”); source(x [which.max(file.info(x)$ mtime)])'假设你在此之前正确设置了wd –

+0

这正是我想要的。谢谢! – stok

回答

0

你可以这样做:

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