【发布时间】:2012-08-21 04:26:49
【问题描述】:
在处理大型代码库时,使用相对路径获取文件非常有用。其他编程语言具有明确定义的机制,用于使用相对于源文件目录的路径来获取文件。一个例子是 Ruby 的require_relative。在 R 中实现相对路径溯源的好方法是什么?
以下是我不久前使用各种食谱和 R 论坛帖子拼凑而成的。它对我来说很适合直接开发,但并不强大。例如,当文件通过testthat 库加载时,它会中断,特别是auto_test()。 rscript_stack() 返回character(0)。
# Returns the stack of RScript files
rscript_stack <- function() {
Filter(Negate(is.null), lapply(sys.frames(), function(x) x$ofile))
}
# Returns the current RScript file path
rscript_current <- function() {
stack <- rscript_stack()
r <- as.character(stack[length(stack)])
first_char <- substring(r, 1, 1)
if (first_char != '~' && first_char != .Platform$file.sep) {
r <- file.path(getwd(), r)
}
r
}
# Sources relative to the current script
source_relative <- function(relative_path, ...) {
source(file.path(dirname(rscript_current()), relative_path), ...)
}
你知道更好的source_relative 实现吗?
【问题讨论】:
-
rscript_stack 是否完全按照此问题的答案中的描述进行操作? stackoverflow.com/questions/1815606/… ... 或者这个:stackoverflow.com/questions/8087743/…
-
你是绝对正确的。事实上,我记得读过@Hadley 对stackoverflow.com/questions/1815606/… 的回答并使用了代码。具有讽刺意味的是,测试代码无法使用。
标签: r