【问题标题】:R: sourcing files using a relative pathR:使用相对路径获取文件
【发布时间】: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 实现吗?

【问题讨论】:

标签: r


【解决方案1】:

在 GitHub 上与@hadley 进行discussion 之后,我意识到我的问题与 R 中的常见开发模式背道而驰。

似乎在 R 文件中,源文件通常假定工作目录 (getwd()) 设置为它们所在的目录。为了使其工作,source 有一个 chdir 参数,其默认值为FALSE。当设置为TRUE时,它会将工作目录更改为正在获取的文件的目录。

总结:

  1. 假设source 始终是相对的,因为正在获取源文件的工作目录设置为文件所在的目录。

  2. 为使这项工作正常进行,当您从另一个目录(例如 source('lib/stats/big_stats.R', chdir=T))获取文件时,请始终设置 chdir=T

为了以可预测的方式方便地获取整个目录,我写了sourceDir,它按字母顺序获取目录中的文件。

sourceDir <- function (path, pattern = "\\.[rR]$", env = NULL, chdir = TRUE) 
{
    files <- sort(dir(path, pattern, full.names = TRUE))
    lapply(files, source, chdir = chdir)
}

【讨论】:

  • @DanChaltiel: `read.csv(./) 我想这就是你要找的东西
猜你喜欢
  • 1970-01-01
  • 2013-01-31
  • 1970-01-01
  • 2017-04-21
  • 1970-01-01
  • 2019-07-13
  • 2018-11-11
  • 1970-01-01
  • 2019-06-30
相关资源
最近更新 更多