我有一个名为的脚本foo.R包含另一个脚本other.R,该脚本位于同一目录中:
#!/usr/bin/env Rscript
message("Hello")
source("other.R")
Run Code Online (Sandbox Code Playgroud)
但我想R发现other.R无论当前的工作目录是什么.
换句话说,foo.R需要知道自己的路径.我怎样才能做到这一点?
在处理大型代码库时,使用相对路径获取文件很有用.其他编程语言具有明确定义的机制,用于使用相对于所源文件的目录的路径来获取文件.一个例子是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), …Run Code Online (Sandbox Code Playgroud)