vkubicki
vkubicki

Reputation: 1124

Subdirectory in R package

I am creating a R package, and would like to organize my R subdirectory, with subdirectories. Since only the function defined in R files at the root directory are exported, I added this code to one file at the root:

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

sourceDir("R/DataGenerator")

When I use "CRTL+SHIFT+B" on RStudio, I see that the nm files are sourced. But once the package is loaded, none of the functions defined in the subdirectory R/DataGenerator are accessible, neither using :: nor using ::: .

How can I export functions defined in subdirectories of R ? Is it even possible ?

Upvotes: 3

Views: 2543

Answers (2)

RBirkelbach
RBirkelbach

Reputation: 101

As indicated in the discussion in the comments to the accepted answer between Martin Morgan and me, this does not seem to work in current R versions. My workaround to get a bit better file organisation is to prefix the filenames using what would have been the subdirectories names.

Upvotes: 2

Martin Morgan
Martin Morgan

Reputation: 46866

Use the Collate: field in the DESCRIPTION file to specify paths to files to be included

Collate: foo.R bar/baz.R

A helper to generate the collate line might be something like

fls = paste(dir(pattern="R", recursive=TRUE), collapse=" ")
cat(strwrap(sprintf("Collate: %s", fls), exdent=4), sep="\n")

Upvotes: 1

Related Questions