3

I wrote a list of different functions and script and I put them in some subfolders of the working directory so I can divide all my functions in arguments (descriptive statistic, geostatistic, regression....)

When I type source("function_in_subfolder") R tells me that there is no function. I understood that it happens because functions have to stay in the working directory. Is there a way to set also subfolders of the working directory as source for the functions (let's say in a hierarchical way)?

4

2 回答 2

5

source函数有一个chdir参数,如果设置为TRUE,会将工作目录设置为脚本所在的目录。新的工作目录在脚本执行期间有效,之后又改回来。假设以下结构

main.R
one/
  script.R
  two/
    subscript.R

您可以source("one/script.R", chdir=T)main.R和 在script.R中调用source("two/subscript.R", chdir=T)

但是,默认情况下,R 将从当前目录开始搜索。没有诸如PATH环境变量之类的“搜索路径列表”之类的东西,尽管显然有人试图创建这样的东西。我强烈建议不要试图在“任何地方”找到脚本文件。相反,请准确指出要在哪个点运行哪个脚本。否则,简单地将文件添加到脚本中导致的名称冲突可能会导致难以调试的不可预知的行为。

于 2013-06-25T23:14:08.153 回答
0

一种解决方案是用来list.files获取函数的完整路径。例如:

    myfunction.path <- list.files(getwd(),
               recursive=TRUE,full.names=TRUE,
              pattern='^myfunction.R$')

然后你可以调用它:

   source(myfunction.path)

的递归调用list.files可能很昂贵,因此也许您应该在分析开始时调用它一次,并将所有函数路径存储在命名列表中。如果您在 2 个不同的子目录中创建 2 个具有相同名称的源文件,请注意结果不能是唯一的。

于 2013-06-25T23:20:23.380 回答