When to use .onLoad vs .onAttach ?

Usually you want .onLoad, which—as the name suggests—runs when the package is loaded. If something has to happen before anything is run, that's the way to go. onAttach only runs when the library is attached, e.g. when somebody calls library(your_package). onLoad will also run when somebody loads but doesn't attach your package by calling your_package::your_function.

Reading:

http://r-pkgs.had.co.nz/r.html#r-differences

http://r-pkgs.had.co.nz/namespace.html#namespace

and the official docs at ?ns-hooks, if you haven't already read that.

4 Likes