R: sourcing files using a relative path

后端 未结 1 1973
半阙折子戏
半阙折子戏 2020-12-12 14:07

Sourcing files using a relative path is useful when dealing with large codebases. Other programming languages have well-defined mechanisms for sourcing files using a path re

相关标签:
1条回答
  • 2020-12-12 14:34

    After a discussion with @hadley on GitHub, I realized that my question goes against the common development patterns in R.

    It seems that in R files that are sourced often assume that the working directory (getwd()) is set to the directory they are in. To make this work, source has a chdir argument whose default value is FALSE. When set to TRUE, it will change the working directory to the directory of the file being sourced.

    In summary:

    1. Assume that source is always relative because the working directory of the file being sourced is set to the directory where the file is.

    2. To make this work, always set chdir=T when you source files from another directory, e.g., source('lib/stats/big_stats.R', chdir=T).

    For convenient sourcing of entire directories in a predictable way I wrote sourceDir, which sources files in a directory in alphabetical order.

    sourceDir <- function (path, pattern = "\\.[rR]$", env = NULL, chdir = TRUE) 
    {
        files <- sort(dir(path, pattern, full.names = TRUE))
        lapply(files, source, chdir = chdir)
    }
    
    0 讨论(0)
提交回复
热议问题