Namespaces and load_all in devtools

devtools is a great R package by Hadley Wickham which helps you create your own packages when developing a project from Day 1. I definitely recommend it, even for beginners. For an introduction to package construction visit Hadley Wickham’s wiki page and when more in-depth knowledge is needed refer to the R Extensions Manual.

What I want to focus on here is a problem you might encounter when using the function load_all to load a source package. load_all simulates the loading of a normal package, by sourcing all the R scripts in the R/ folder, loading all the data in the data/ folder and compiling (and attaching the resulting so/dll) all the source code in the src/ folder. However I had trouble (as had many) importing the namespace of other packages for use with your custom-built one.

The problem

Consider the simple function

myrowsum <- function(Q) {

where Q is expected to be a sparse matrix of class dgCMatrix defined in package Matrix. There are many suggested steps to make this happen.
1. Add Matrix to the Depends field in the DESCRIPTION file.
2. Add import(Matrix) to the NAMESPACE file or simply
3. Add importFrom(Matrix,rowSums) to the NAMESPACE file (or using roxygen2 as described here)

However, none of these had the desirable effect of loading the Matrix namespace. Adding  print(environment(rowSums)) to the function above revealed that in fact rowSums belonged to the environment namespace:base. This code would not work for sparse matrices.

To load the namespace of the desired package, the only way I tried which worked was by adding Matrix to the Imports field in the DESCRIPTION file. This had the desired effect of associating rowSums with the correct namespace; I used this approach for all other packages in my project which now are working fine.