Using R's `sourceDir` Function to Include Files from a Library Directory

Using R’s sourceDir Function to Include Files from a Library Directory

As R users, we often find ourselves working with multiple scripts and libraries. Having a way to easily include these files without having to use fully qualified names can be a huge productivity booster. In this article, we’ll explore how to achieve this using R’s built-in sourceDir function.

Introduction to the Problem

Let’s say you have a set of frequently used functions saved in separate .r script files, and they’re all located in a library directory (~/r_lib/). You want to be able to include these files in your R code without having to use the fully qualified name. For example, instead of source("path/to/file1.r"), you’d like to use just file1(). This is similar to the behavior of the C++ compiler’s -I flag.

Understanding the Solution

The solution involves using R’s built-in sourceDir function from the utils package. This function allows you to specify a directory and automatically includes all files with a .r extension in that directory into your current environment.

Here’s an example implementation of the sourceDir function:

## Define the sourceDir function
sourceDir <- function(path, trace = TRUE, ...) {
  for (nm in list.files(path, pattern = "\\.[RrSsQq]$")) {
    if(trace) cat(nm,":")           
    source(file.path(path, nm), ...)
    if(trace) cat("\n")
  }
}

This function takes three arguments:

  • path: the directory containing the files to be included
  • trace: a logical value indicating whether to print the name of each file being sourced (defaults to TRUE)
  • ...: additional arguments that can be passed to the source function

Using sys.source for Clean Global Environment

When using sourceDir, it’s recommended to use sys.source instead of simply calling source. This is because sys.source does not clutter your global environment with extra objects, whereas source creates a new object in the search path.

Here’s an example:

## Use sys.source within sourceDir
sourceDir <- function(path, trace = TRUE, ...) {
  for (nm in list.files(path, pattern = "\\.[RrSsQq]$")) {
    if(trace) cat(nm,":")           
    sys.source(file.path(path, nm), ...)
    if(trace) cat("\n")
  }
}

By using sys.source, we ensure that our functions are defined locally and do not pollute the global environment with extra objects.

Setting up the Library Directory

To use sourceDir, you’ll need to set up your library directory. This can be done in your .Rprofile file or .Renviron file. Here’s an example of how to add the following line to your .Rprofile file:

## Add the library directory to the search path
setwd("~/r_lib")

This sets the working directory to ~/r_lib/, which is where you’ll be looking for files with a .r extension.

Putting it all Together

Here’s an example of how you might use sourceDir in your R code:

## Load the sourceDir function
sourceDir <- system.file("utils", "sourceDir.R")

## Set up the library directory
setwd("~/r_lib")

## Include files from the library directory using sourceDir
sourceDir()

This code loads the sourceDir function, sets up the library directory, and then calls sourceDir() to include all files with a .r extension in that directory.

Benefits of Using sourceDir

Using sourceDir provides several benefits:

  • Convenience: You can easily include multiple files without having to use fully qualified names.
  • Productivity: By automating the process, you’ll save time and reduce clutter in your code.
  • Flexibility: You can customize the behavior of sourceDir by passing additional arguments.

Common Use Cases for sourceDir

Here are some common use cases for sourceDir:

  • Personal libraries: If you have a set of frequently used functions, consider storing them in a library directory and using sourceDir to include those files.
  • Package development: When developing packages, it’s often useful to include example code or dependencies that can be easily included using sourceDir.
  • Automating workflows: By automating the process of including files, you can streamline your workflow and reduce the time spent on manual work.

Conclusion

In this article, we explored how to use R’s built-in sourceDir function to include files from a library directory. We covered the basics of the function, its benefits, common use cases, and provided examples to get you started. By leveraging sourceDir, you can save time, increase productivity, and streamline your workflow.

Additional Resources

For more information on R’s source functions, be sure to check out the following resources:


Last modified on 2025-04-15