如何通过shell从父目录中获取R文件?

Min*_*now 3 shell r

我可以从IDE(Rstudio)中获取R脚本,但不能从命令行调用中获取.有没有办法做到这一点,而无需提供完整的路径?

我想要源的文件位于父目录中.

这有效:

source('../myfile.R')  #in a call from Rstudio
Run Code Online (Sandbox Code Playgroud)

但是,这不是:

>  Rscript filethatsources_myfile.R

Error in file(filename, "r", encoding = encoding) : 
  cannot open the connection
Calls: source -> file
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file '../myfile.R': No such file or directory
Execution halted
Run Code Online (Sandbox Code Playgroud)

这似乎应该很简单,但......

编辑:我正在使用GNU bash,版本3.2.53(1)-release(x86_64-apple-darwin13)

Ale*_* A. 10

在R中,相对文件位置始终相对于当前工作目录.您可以像这样显式设置工作目录:

setwd("~/some/location")
Run Code Online (Sandbox Code Playgroud)

设置完成后,您可以获取相对于当前工作目录的源文件.

source("some_script.R")         # In this directory
source("../another_script.R")   # In the parent directory
source("folder/stuff.R")        # In a child directory
Run Code Online (Sandbox Code Playgroud)

不确定您当前的工作目录是什么?您可以通过提交进行检查getwd().

如果源文件位于(例如)父目录但引用相对于其位置的文件,怎么办?使用以下chdir=选项source:

source("../another_script.R", chdir = TRUE)
Run Code Online (Sandbox Code Playgroud)

这会在源评估期间临时将工作目录更改为包含源文件的目录.完成后,您的工作目录将恢复到运行之前的状态source.