【问题标题】:source(..., chdir=TRUE) does not seem to change the directorysource(..., chdir=TRUE) 似乎没有改变目录
【发布时间】:2013-11-01 15:16:39
【问题描述】:

我对 R 很陌生,我正在尝试获取一个文件,该文件又是一个源文件。所以我有一个文件,我们称之为mother.R,其中包含一个源调用:

source ("grandmother.R")

mother.R 和祖母.R 在同一个目录中。

我现在想获取mother.R:

source ("C:/Users/whatever/R/mother.R", chdir=T)

我的假设是chdir=T 会导致在C:/Users/whatever/R/ 下查找源中的源,但是在像这样采购时它没有找到祖母.R。我误会chdir了吗?有没有办法做到这一点而不必在mother.R中使用绝对路径?

【问题讨论】:

  • 目前还不清楚你真正想要做什么,但我相信chdir=T 只会在mother.R 中的代码运行时影响工作目录,而不是之后。但总的来说,没有充分的理由在函数或脚本中使用source。如果您能解释您的目标是什么,我们可以建议一种更有效的方法。
  • @CarlWitthoft 我很惊讶你说没有充分的理由使用source。有没有更好的方法将代码拆分成多个文件?
  • @Matthew 为什么要将一起运行的代码拆分为单独的文件?但也许更好的问题是“OP 文件中的内容是什么?” .通常你应该构建一个 package 以便所有需要的函数都在同一个命名空间中。从宏(脚本)运行代码是不好的做法。

标签: r chdir


【解决方案1】:

您对source 工作原理的理解对我来说似乎是正确的。但是让我们编写一个示例,以便您可以与您的设置进行比较,并可能找出您出错的地方。

/Users/me/test/mother.R 文件包含以下内容:

print("I am the mother")
print(paste("The current dir is:", getwd()))
source("grandmother.R") # local path

并让/Users/me/test/grandmother.R 文件包含以下内容:

print("I am the grandmother")

从哪里开始有助于理解:

> getwd()
[1] "/Users/me"

这不起作用:

> source("/Users/me/test/mother.R")
[1] "I am the mother"
[1] "The current dir is: /Users/me"
Error in file(filename, "r", encoding = encoding) : 
  cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file 'grandmother.R': No such file or directory

因为 R 在 getwd() 目录中寻找 grandmother.R...

相反,

> source("/Users/me/test/mother.R", chdir = TRUE)
[1] "I am the mother"
[1] "The current dir is: /Users/me/test"
[1] "I am the grandmother"

之所以有效,是因为source() 临时将当前目录更改为/Users/me/test/,它可以在其中找到grandmother.R

source 将句柄还给你时,你会回到你开始的地方,这意味着chdirsource 调用的本地地址,就像@CarlWitthoft 指出的那样。

> getwd()
[1] "/Users/me"

【讨论】:

  • 感谢弗洛德尔的帮助。感谢您的简单示例,我找到了它在我的情况下不起作用的原因。我在mother.R 的函数中使用source("grandmother.R") 时犯了一个错误。如果在调用此功能之前未调用源,则chdir 自然不适用。我需要在任何函数的定义之外调用源代码。
  • 一般来说,在函数中获取脚本似乎不是一个好主意,因为我只需要自己学习。
猜你喜欢
  • 1970-01-01
  • 2013-07-10
  • 2021-07-17
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-06
  • 1970-01-01
相关资源
最近更新 更多