How to manage multiple user defined functions ?


I am unsure on exactly what to categorize my question under, but I will go ahead and ask anyways. If i had multiple user defined functions, is it possible to manage them under a namespace / one script ? I don't know what the equivalent in R is ?
In JMP , the tool I am familiar with, I can define multiple user defined functions under one namespace. When I include the namespace in my script, I have access to all the functions. I am not sure if all these functions need to be wrapped into a package and how much work that would entail. Kindly offer any guidance.



I would consider creating your own package. While it may sound like a lot of work, it's a breeze with usethis:


That line will create everything you need to start developing your package. From this point, you can start saving your functions in the R directory. Use #' @export to be able to call on these functions when loading your package or don't and those functions will be internal.

If you don't want to create a package, I think one option would be to save your functions in some folder and then source them at the beginning of your script with source.


I second @tyluRp - if you have functions that you will only use in one project, I would keep them organized in a source/ folder (following "Good Enough Practices in Scientific Computing"):

| project/
| -- data/
| ---- data.csv
| -- docs/
| ---- notebook.Rmd
| -- source/
| ---- create_data.R
| ---- clean_logical.R
| -- project.Rproj

You can call these from the top of your notebook.Rmd with source(here::here("source", "create_data.R")).

If you are going to use these same functions across projects, a package is a far better bet. We recently had an excellent thread on a very similar topic. Here are a couple of takeaways that were mentioned:

  1. While package development seems difficult, it does not have to be!
  2. @jrlewi recommends using Git to track your package, and I would add that keeping it stored on GitHub is an excellent idea as well
  3. don't worry about complying with CRAN requirements at the outset, or about using things like unit testing, continuous integration, and code coverage
    • I would, however, suggest that passing devtools::check() without warnings or errors is a good metric for success

If you want something to look at for a bit of inspiration, I have a small package that I named after myself on GitHub. I have no intention of ever submitting it to CRAN, but I use to to store a few "general" functions that I find useful across many projects or tasks.

Some package development resources from the same thread as above:

And finally, make sure you have usethis, devtools, and roxygen2 installed! They're all very helpful for different facets of package development.