[R-pkg-devel] Conditional use of suggested package in example code

Christian Sigg li@t@ @ending from @igg-iten@ch
Wed May 30 11:08:38 CEST 2018


I am updating the ’nsprcomp’ package to follow the recommendations of Section 1.1.3.1 of the Writing R Extensions manual.

Before the update, the example code for the `nsprcomp` function looked like this:

> library(MASS)
> set.seed(1)
> 
> # Regular PCA, with the tolerance set to return five PCs
> prcomp(Boston, tol = 0.36, scale. = TRUE)
> 
> # Sparse PCA with different cardinalities per component. The number of components
> # is derived from the length of vector k.
> nsprcomp(Boston, k = c(13, 7, 5, 5, 5), scale. = TRUE)  
> 
> (…)

The unconditional use of the suggested package ‘MASS’ produces an error on systems where ‘MASS’ is not installed. 

I personally think that this is fine in an interactive session. The error makes it obvious what the user has to do to run the example - install the missing package. But I understand that it would increase the complexity of automated checking of examples, where one would have to distinguish between this kind of error and an actual bug in the example code.

In any case, the WRE manual recommends conditional use of suggested packages via `requireNamespace`. A straightforward way to follow the recommendation is to wrap the whole example in a conditional statement:

> if (requireNamespace("MASS", quietly = TRUE)) {
>  set.seed(1)
> 
>  # Regular PCA, with the tolerance set to return five PCs
>  prcomp(MASS::Boston, tol = 0.36, scale. = TRUE)
> 
>  # Sparse PCA with different cardinalities per component. The number of components
>  # is derived from the length of vector k.
>  nsprcomp(MASS::Boston, k = c(13, 7, 5, 5, 5), scale. = TRUE)  
> 
>  (…)
> }

I don’t like this for two reasons:

1. The if statement and the indentation add clutter to the example code, making the help page harder to read.

2. The if statement breaks the output of `example(“nsprcomp”, “nsprcomp”)`. Now only the statement before the closing curly brace has its output printed to the console. I would have to add explicit print statements that further clutter up the example.

Is there a coding pattern that satisfies the WRE recommendations, but avoids these two problems?

Regards
Christian

—
Christian Sigg
https://sigg-iten.ch/research



More information about the R-package-devel mailing list