質問

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)?

役に立ちましたか?

解決

The source function has a chdir argument which, if set to TRUE, will set the working directory to that where the script resides. The new work directory is valid for the duration of the execution of the script, after that it is changed back. Assumung the following structure

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

you can call source("one/script.R", chdir=T) from main.R and, in script.R, call source("two/subscript.R", chdir=T).

However, by default, R will start its search from the current directory. There is no such thing as a "list of search paths" like, e.g., the PATH environment variable, although apparently someone attempted to create such a thing. I would strongly advise against attempting to find a script file "anywhere". Instead, indicate precisely which script is to be run at which point. Otherwise, name clashes resulting from simply adding a file to your scripts can lead to unpredictable behavior which is also difficult to debug.

他のヒント

One solution is to use list.files to get the full path of your function. for example:

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

Then you can call it :

   source(myfunction.path)

The recursive call of list.files can be expensive, so maybe you should call it once at the beginning of your analyze for example and store all functions paths in a named list. And BE CAREFUL the result can not be unique if you create 2 sources files withe the same name in 2 differents sub-directories.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top