gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:27:43 24 4
gpt4 key购买 nike

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

我要获取的文件位于父目录中。

这有效:

source('../myfile.R')  #in a call from Rstudio

但是,这不会:
>  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

这看起来应该很简单,但是......

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

最佳答案

在 R 中,相对文件位置总是相对于当前工作目录。您可以像这样显式设置您的工作目录:

setwd("~/some/location")

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

source("some_script.R")         # In this directory
source("../another_script.R") # In the parent directory
source("folder/stuff.R") # In a child directory

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

例如,如果您的源文件在父目录中但引用了与其位置相关的文件,该怎么办?使用 chdir= source 中的选项:

source("../another_script.R", chdir = TRUE)

这会在源评估期间暂时将工作目录更改为包含源文件的目录。完成后,您的工作目录将设置回运行之前的目录 source .

关于r - 如何通过 shell 从父目录获取 R 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29977769/

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