gpt4 book ai didi

R:使用相对路径获取文件

转载 作者:行者123 更新时间:2023-12-02 03:38:36 24 4
gpt4 key购买 nike

在处理大型代码库时,使用相对路径获取文件非常有用。其他编程语言具有明确定义的机制,用于使用相对于所获取文件的目录的路径来获取文件。 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 实现吗?

最佳答案

discussion之后通过 GitHub 上的 @hadley,我意识到我的问题违背了 R 中的常见开发模式。

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

总结:

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

  2. 要实现此目的,请在从其他目录获取文件时始终设置 chdir=T,例如 source('lib/stats/big_stats.R', 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)
}

关于R:使用相对路径获取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12048436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com