相关疑难解决方法(0)

R命令用于在Rstudio中将工作目录设置为源文件位置

我正在研究R中的一些教程.每个R代码都包含在一个特定的文件夹中.那里有数据文件和其他文件.我想打开.r文件并获取它,这样我就不必更改Rstudio中的工作目录,如下所示:

在此输入图像描述

有没有办法在R中自动指定我的工作目录

automation r working-directory

118
推荐指数
10
解决办法
9万
查看次数

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)

r

57
推荐指数
1
解决办法
4万
查看次数

确定当前文件在R中的位置以包含来自同一目录的文件?

我希望能够source()在同一目录中包含不同文件的文件,但我不想在运行此文件之前从R-prompt设置工作目录:

> getwd()
[1] "/Users/myser"
> source("/Users/myuser/workspace/myproject/myfile.r")
Run Code Online (Sandbox Code Playgroud)

在/ Users/myuser/workspace/myproject里面,会有myfile.r和my-utils.r.myfile.r source('my-utils.r')从中调用.

其他编程语言可以确定当前文件的路径.R有类似的东西吗?例:

cur_dir <- sys.get_current_file_path()
source(file.path(cur_dir, "my-utils.r"))
Run Code Online (Sandbox Code Playgroud)

filesystems r system

10
推荐指数
1
解决办法
4304
查看次数

标签 统计

r ×3

automation ×1

filesystems ×1

system ×1

working-directory ×1