3

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 ?

1
  • 1
    The lack of proper support for nested package hierarchy was one of the reasons that prompted me to write modules, which implements a superior, Python-like package/module system for R. You may want to give it a shot. Commented Nov 18, 2015 at 11:54

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

3 Comments

That is one elegant piece of code — just beware that your pattern is too broad, it will capture non-R source files (and it’s case sensitive so it will miss all source files that don’t use a capital-R extension). It should be '\\.[rR]$'.
Can you please show us an example R package where this worked? When I try to follow your approach I get the error Error in .install_package_code_files(".", instdir) : files in 'Collate' field missing from '/home/user/packagename/R': subdir/code.R ERROR: unable to collate and parse R files for package packagename
Actually I'm not sure that I can help; it seems like the kind of thing that I wouldn't have just made up or thought that I knew, but you're right that with current R this definitely does not work. The parallel package and documentation suggest that this works only for OS-specific (windows, unix) subdirectories...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.