Purging previous versions of functions when developing packages in R

package, r

Solution

You need to try to unload the package as well as detach it. `?detach` has:

If a package has a namespace, detaching it does not by default unload the namespace (and may not even with ‘unload=TRUE’), and detaching will not in general unload any dynamically loaded compiled code (DLLs). Further, registered S3 methods from the namespace will not be removed. If you use ‘library’ on a package whose namespace is loaded, it attaches the exports of the already loaded namespace. So detaching and re-attaching a package may not refresh some or all components of the package, and is inadvisable.

Note the last sentence in particular.

Try:

detach(package:mypkg, unload = TRUE)

Note that the "If a package has a namespace" now means all packages as this was changed in R 2.14.0 (IIRC the version number)

If the code you are changing is R code, consider using `assignInNamespace()` to assign an object/function in your global workspace (i.e. the newer version of function in `mypkg`) to the namespace of `mypkg`. For example we have function `foo()` in `mypkg` and locally we have `newfoo()` which is the newer version of `foo()`:

assignInNamespace("foo", newfoo, "mypkg")

If the changes relate to C code, or the above don't work, then perhaps you should follow the advice of R Core and spawn a new R instance instead of trying to detach your package.

See also the devtools package of Hadley Wickham and Emacs+ESS might make the development process easier (spawning new R instances etc) if you speak Emacs.

Problem

I am developing a package in R. Let's call it `mypkg`. Because some functions behave differently when they are run from a package (I am not sure why--but this is not the question), I am editing functions in the package, then rebuilding the package from the command line. For some reason a given R instance retains older versions of the functions even though the source has been changed and the package rebuilt and re-installed. I need to start a new instance to see the changes. Here is the typical workflow. - Make changes to `myfunction()` in `mypkg.R` - In R: `detach(package:mypkg); remove.packages("mypkg")` - Command line: `R CMD INSTALL --build c:\mypkg` - Notifies me that it has been installed to the default library - In R: `library(mypkg)` - In R: `myfunction()` runs the previous version before changes. [The next three steps I want to avoid] - Start a new R instance - In R: `library(mypkg)` - `myfunction()` works as expected Run under R.2.14.1. I am looking for suggestions of how to improve this workflow to avoid starting a new R instance.

Original source