我希望以编程方式获取包含在使用Sys.glob()函数检索的给定数组中的所有.R文件。
这是我写的代码:
# fetch the different ETL parts
parts <- Sys.glob("scratch/*.R")
if (length(parts) > 0) {
for (part in parts) {
# source the ETL part
source(part)
# rest of code goes here
# ...
}
} else {
stop("no ETL parts found (no data to process)")
}我遇到的问题是我不能这样做,或者,至少,我得到以下错误:
simpleError in source(part): scratch/foo.bar.com-https.R:4:151: unexpected string constant我尝试了source()函数的不同组合,如下所示:
source(sprintf("./%s", part))
source(toString(part))
source(file = part)
source(file = sprintf("./%s", part))
source(file = toString(part))不走运。当我处理一个目录的内容时,我需要告诉R将这些文件作为源文件。因为它是一个定制的ETL (提取、转换和加载)脚本,所以我可以手动编写:
source("scratch/foo.bar.com-https.R")
source("scratch/bar.bar.com-https.R")
source("scratch/baz.bar.com-https.R")但这是肮脏的,现在有3种不同的提取模式。它们可能是8种,80种,甚至2000种不同的模式,所以手写是不可行的。
我该怎么做呢?
发布于 2019-02-14 18:59:44
尝试使用dir获取文件列表,然后使用lapply:
例如,如果您的文件格式为t1.R、t2.R等,并且位于路径"StackOverflow“中,请执行以下操作:
d = dir(pattern = "^t\\d.R$", path = "StackOverflow/", recursive = T, full.names = T)
m = lapply(d, source)选项recursive = T将搜索所有子目录,full.names = T将向文件名添加路径。
如果您仍然想使用Sys.glob(),也可以使用此方法:
d = Sys.glob(paths = "StackOverflow/t*.R")
m = lapply(d, source)https://stackoverflow.com/questions/54688532
复制相似问题