Loading R package in vignette for the package itself - r

I am currently building an R package, call it mypackage. I generated a package vignette using devtools::use_vignette("my-vignette"), and filled in my-vignette with content. Of course, because it is a package vignette, I need to demonstrate the use of the functions and data contained in this package itself. However, I'm having issues loading the package and its contents when knitting the vignette.
All of the code chunks in the vignette run without error on my local computer, even after restarting R and clearing the workspace. However, when I attempt to build the package using devtools::build(), the build fails with:
Error in library(mypackage): there is no package called `mypackage` Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> library Execution halted
The full output in the Console from devtools::build() is:
* checking for file ‘/path/to/mypackage/DESCRIPTION’ ... OK
* preparing ‘mypackage’:
* checking DESCRIPTION meta-information ... OK
* installing the package to build vignettes
* creating vignettes ... ERROR
Quitting from lines 39-44 (my-vignette.Rmd)
Error: processing vignette 'my-vignette.Rmd' failed with diagnostics:
'my_function' is not an exported object from 'namespace:mypackage'
Execution halted
devtools::document() runs without error, but devtools::build_vignettes() aparently reaches a different error where it cannot use a specific function (but seems to be able to load the package itself):
> devtools::build_vignettes()
Building mypackage vignettes
Moving basic-mypackage-vignette.html, basic-mypackage-vignette.R to inst/doc/
Copying basic-mypackage-vignette.Rmd to inst/doc/
> devtools::build()
'/Library/Frameworks/R.framework/Resources/bin/R' --no-site-file --no-environ --no-save --no-restore --quiet CMD build \
'/path/to/mypackage' --no-resave-data --no-manual
* checking for file ‘/path/to/mypackage/DESCRIPTION’ ... OK
* preparing ‘auctestr’:
* checking DESCRIPTION meta-information ... OK
* installing the package to build vignettes
* creating vignettes ... ERROR
Quitting from lines 39-44 (my-vignette.Rmd)
Error: processing vignette 'my-vignette.Rmd' failed with
diagnostics:
could not find function "my_function"
Execution halted
Error: Command failed (1)
> devtools::document()
Updating mypackage documentation
Loading mypackage
I assume this is because the package itself does not exist in my R library; I am just loading that package using devtools::load_all() when doing development. How can I get around this and load my package in order to use its functions and data in the package vignette? Specifically, how can I make the package in its functions available to whatever environment knitr is using to knit the vignette?
I have seen other package vignettes load the package directly using library() without issue; for example, in the stringr vignette.
I hope readers can evaluate this without a fully reproducible example; reproducing the entire example is difficult because it requires a full R package directory structure that is difficult to replicate or share here.

I do load directly my package in my vignettes (library(my_package)).
But considering your error, it might not be the problem...
Can you make sure that my_function is indeed exported. You should add the following code ate the end of the documentation of your function.
#' #export

I added a chunk
```{r, include=FALSE}
devtools::load_all(".")
```
at the beginning of the vignette to work around the problem.
However, this doesn't fix the actual problem, as this should not be necessary.

Alternatively you could use the ::: notation, especially if you are not exporting that function, e.g.
mypackage:::my_function()

Related

Cannot install vignette from an R package on GitHub

I coded an R package that is hosted on my GitHub. I included a vignette, and I can install the package and load the vignette without any issue from R and RStudio by doing:
devtools::install_github("rosalieb/serac", build_vignettes = TRUE)
library(serac)
vignette("serac")
However, I have a few colleagues who cannot install the vignette (the only way they can download the package is by doing devtools::install_github("rosalieb/serac") (default of build_vignettes is FALSE).
It works if they use RStudio, but not in 'regular' R.
I encourage people to use RStudio, but I cannot force them, and eventually, I do not understand why it would work in 'regular' R for me but not for them.
They tried to install pandoc, knitr, Rtools - none of these worked.
Here is the error message when my colleague tries to install the package with the vignette:
v checking for file 'C:\Temp\RtmpO8YwVb\remotesf9842f1431\rosalieb-serac-46a3587/DESCRIPTION'
- preparing 'serac':
checking DESCRIPTION meta-information ...
checking DESCRIPTION meta-information ...
v checking DESCRIPTION meta-information
- installing the package to build vignettes
creating vignettes ...
creating vignettes ...
E creating vignettes (4.9s)
--- re-building 'serac.Rmd' using rmarkdown
Error: processing vignette 'serac.Rmd' failed with diagnostics:
Pandoc is required to build R Markdown vignettes but not available. Please make sure it is installed.
--- failed re-building 'serac.Rmd'
RESUME : le traitement du fichier suivant a échoué :
'serac.Rmd'
Erreur : Vignette re-building failed.
Exécution arrêtée
Erreur : Failed to install 'serac' from GitHub:
System command 'Rcmd.exe' failed, exit status: 1, stdout & stderr were printed
Thanks in advance for your help!
The message indicates that rmarkdown::render can't find Pandoc.
It looks for it in three places: in the directory specified by the RSTUDIO_PANDOC environment variable, in directories on the PATH, in the directory opt/pandoc in the user's home directory. So your colleagues who have installed it should make sure it is available in one of those locations. They can see the current values of the environment variables by running
Sys.getenv("PATH")
and
Sys.getenv("RSTUDIO_PANDOC")
Temporary changes can be made using
Sys.setenv(RSTUDIO_PANDOC="/path/to/pandoc/directory")
This needs to happen in the session that is trying to install the package and build the vignette, not in the vignette itself.
How to make permanent changes to those values depends on the details of what system they are running.

roxygen2 not creating .Rd documentation

I am unable to generate .Rd documentation files for my package using RStudio and Roxygen2. First, let me mention that I have gone through similar problems posted here and have already done the following:
Roxygen2 blocks initiated at the beginning of file with a #'
Configured Build Tools>Checked generate documentation with Roxygen> Configure > Checked all fields under 'Use roxygen to generate' and 'Automatically roxygenize when running'
Made sure there were no .Rd files in the 'man' folder
And even after that, when I perform a 'Build and Reload' on RStudio I get the following output (please note the line that reads: No man pages found in package MYPACKAGE:
=
=> devtools::document(roclets=c('rd', 'collate', 'namespace', 'vignette'))
>
Updating MYPACKAGE documentation
Loading MYPACKAGE
Documentation completed
==> Rcmd.exe INSTALL --no-multiarch --with-keep.source MYPACKAGE
installing to library C:/Users/user/Documents/R/win-library/3.3
installing source package 'MYPACKAGE' ...
** R
** data
* moving datasets to lazyload DB
** preparing package for lazy loading
No man pages found in package 'MYPACKAGE'
** help
* installing help indices
** building package indices
** testing if installed package can be loaded
DONE (MYPACKAGE)
Edit:
Upon further investigation, it appears that this was caused by the fact that I have sub-directories within my R directory, which is not supported by default. A possible solution was located here which, however, I haven't yet tried out. I will report back with the outcome as soon as I am able to perform the tests.
I had the same error. roxygen2 was creating correctly the md files in the /man directory but they were not found at compilation time. I had the following error.
No man pages found in package
After a bit of time I found that in one of the R file I had a source statement
source("C:/Users/vaulot/Google Drive/Scripts/R library/dv_function_pr2.R")
My guess is that there was some code in the source file interfering with roxygen2.

R can't find packages installed by travis

We're trying to add some unit tests to the caret package that get run by travis, but not on CRAN. This saves build time on CRAN and reduces the number of dependencies they have to install to check our package, while letting us run a more complete test suite on travis.
I thought I could simply install the requirements for the test using the r_packages: line in my travis.yml file:
r_packages:
- ROSE
- DMwR
However, my NOT_CRAN=TRUE builds are still failing. (NOT_CRAN=FALSE runs fine as the problematic tests are skipped)
This is really strange, as when I look at the build logs, I see travis successfully installing all the packages I need:
* installing *source* package ‘ROSE’ ...
** package ‘ROSE’ successfully unpacked and MD5 sums checked
** R
** data
** inst
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded
* DONE (ROSE)
But when my tests run that depend on those packages, R can't find them:
> library(testthat)
> library(caret)
Loading required package: lattice
Loading required package: ggplot2
>
> test_check("caret")
[1] "Reduced dimension to 3 by default. "
1 package is needed for this model and is not installed. (ROSE). Would you like to try to install it now?1. Error: check appropriate sampling calls by name -----------------------------
1: withCallingHandlers(eval(code, new_test_environment), error = capture_calls, message = function(c) invokeRestart("muffleMessage"),
warning = function(c) invokeRestart("muffleWarning"))
2: eval(code, new_test_environment)
3: eval(expr, envir, enclos)
4: caret:::parse_sampling(i) at test_sampling_options.R:14
5: checkInstall(pkgs)
6: stop()
testthat results ================================================================
OK: 62 SKIPPED: 0 FAILED: 1
1. Error: check appropriate sampling calls by name
Error: testthat unit tests failed
Execution halted
(I think) the relevant line of code is here in caret's source code:
good <- rep(TRUE, length(pkg))
for(i in seq(along = pkg)){
tested <- try(find.package(pkg[i]), silent = TRUE)
if(class(tested)[1] == "try-error") good[i] <- FALSE
}
Why can't the find.package function find packages installed by travis? Do they go in a special, separate library somewhere?
Also, as an aside, how do I make my travis builds for r less verbose? By default they seem to print way too much information (e.g. it echoes all code run by the tests and manual, even code that doesn't error).
When testing your package on Travis, R CMD check appears to be looking for installed packages in the wrong place(s).
I created a small test package to figure this out:
When testing the package on Travis using R CMD check, .libPaths() contains:
c("/tmp/RtmpnQE1WM/RLIBS_29bd3940b7fa",
"/usr/lib/R/library")
When testing the package on Travis using devtools::test(), .libPaths() contains:
c("/usr/local/lib/R/site-library",
"/usr/lib/R/site-library",
"/usr/lib/R/library")
By default, R packages on Travis are installed into /usr/local/lib/R/site-library (i.e. the first entry of .libPaths()). Clearly, R CMD check is looking in the wrong place(s).
In principle, we could use the --library argument for R CMD check to point to the right place, however when you use --as-cran then --library defaults to /usr/lib/R/library.
The easiest solution is probably to install all packages (in particular the "additional" packages ROSE and DMwR) into /usr/lib/R/library. There are many ways to do that. One solution is to add
sudo mkdir -p /usr/lib/R/library
echo 'R_LIBS=/usr/lib/R/library:/usr/lib/R/site-library/' > ~/.Renviron
sudo chmod 2777 /usr/lib/R/library
to the before_install section of your .travis.yml file.
You could clone the r-travis repo and just source from your copy. That would allow you to make it less verbose.
As to "packages not found": dunno. But the Travis instance is a vanilla Ubuntu installation so you can control things by echo'ing into a suitable ~/.Rprofile etc pp. I have found the old r-travis setup to be more convenient for me and recently blogged about one way to dramatically cut test times down by relying more on pre-built r-cran-* .deb packages.
Michael has well over 1000 in his repo, and you could build your own too via a PPA. Time permitting I may write another blog post detailing that...

Error: processing vignette ...: 'what' must be a character string or a function

I'm trying to tie up the loose ends of a package, and I'm pretty much down to just the vignettes. I have four vignettes in the package. For references we'll call them Vignettes A - D. When I run R CMD check, I get the error
Error: processing vignette 'Vignette A.Rmd' failed with diagnostics:
'what' must be a character string or a function
However, anytime I process Vignette A by using the knit button in R Studio, the document compiles just fine.
So I started playing around and eventually, I found that R CMD check fails anytime I have both Vignettes A and C in the package. But any time I remove either one of those two vignettes, R CMD check passes with no errors.
I haven't any clue where to start on this one. Any ideas on what could be the problem with these two files coexisting in a package?
I'm using R 3.2.0.
The package in question is in the development branch at
Github
Output from .Rcheck log file
* checking files in 'vignettes' ... OK
* checking examples ... OK
* checking for unstated dependencies in vignettes ... OK
* checking package vignettes in 'inst/doc' ... WARNING
Package vignettes without corresponding PDF/HTML:
'DecisionNetworks.Rmd'
'GettingStartedWithHydeNet.Rmd'
'HydeNetPlots.Rmd'
'WorkingWithHydeNetObjects.Rmd'
* checking running R code from vignettes ... OK
* checking re-building of vignette outputs ... NOTE
Error in re-building vignettes:
...
Loading required package: nnet
Loading required package: rjags
Loading required package: coda
Linked to JAGS 3.4.0
Loaded modules: basemod,bugs
Quitting from lines 173-176 (WorkingWithHydeNetObjects.Rmd)
Error: processing vignette 'WorkingWithHydeNetObjects.Rmd' failed with diagnostics:
'what' must be a character string or a function
Execution halted
Yuhui's hint got me to the solution. At first, I ran knitr::knit('vignettes/WorkingWithHydeNetObjects.Rmd') and everything worked fine. Then I tried running knit on the other vignette with the coexistence problem and found no errors. Then I ran knit on WorkingWithHydeNetObjects.Rmd again, and this time the error was produced.
traceback identified the error as coming from do.call. I was passing a missing argument to do.call when it should have been passing a character string. The behavior of the functions was changed by changing and option in the other vignette.
So the moral of the story is not to assume that each vignette will be built in its own environment. Any options you set in one vignette will be carried over into subsequent vignettes.

"'knitr' not found" error during package / vignette build

I'm using knitr to build an R package vignette. This process worked before R 3.0, but I haven't been able to rebuild the package under R 3.1.1.
When I try R CMD build I get an error message:
R CMD build Causata
* checking for file ‘Causata/DESCRIPTION’ ... OK
* preparing ‘Causata’:
* checking DESCRIPTION meta-information ... OK
* installing the package to build vignettes
* creating vignettes ...
ERROR Error in loadVignetteBuilder(vigns$pkgdir) :
vignette builder 'knitr' not found Calls: <Anonymous> -> loadVignetteBuilder
In addition:
Warning message: In tools::buildVignettes(dir = ".", tangle = TRUE) :
Files named as vignettes but with no recognized vignette engine:
‘vignettes/Causata-vignette.rnw’ (Is a VignetteBuilder field missing?)
Execution halted
My vignette file has a VignetteEngine call -- here are the first three lines:
% !Rnw weave = knitr
%\VignetteEngine{knitr::knitr}
%\VignetteIndexEntry{Model training and export}
My package description file includes a VignetteBuilder field:
VignetteBuilder: knitr
I think I'm following the instructions for Rnw vignettes, so I'm baffled by the error message I'm seeing.
Incidentally, if I try to build the vignette directly then everything seems to work perfectly. This command generates the vignette PDF:
tools::buildVignettes(dir=".", tangle=TRUE)
My trouble seems to be only with R CMD build. Why won't the build work?
Here's my complete package DESCRIPTION file for reference:
Package: Causata
Type: Package
Title: Analysis utilities for binary classification and Causata users.
Version: 5.0-1
Date: 2014-10-09
Author: Justin Hemann, David Barker, Suzanne Weller, Jason McFall
Maintainer: Justin Hemann <justin.hemann#nice.com>
Description: The Causata package provides utilities for
extracting data from the Causata application, training regression / classification
models, and exporting models as PMML for scoring.
Depends: R (>= 2.15.1)
Imports: XML, R.utils, rjson, RCurl, stringr, yaml, boot, foreach, data.table, glmnet, ggplot2, methods
Suggests: knitr, doMC, testthat, pROC, RODBC, RMySQL
VignetteBuilder: knitr
License: GPL
LazyLoad: yes
URL: www.nice.com
According to the feedback of Josh O'Brien, I guess you might have the same issue as him. If you want to add some custom library paths, I'd recommend you to do it in ~/.Renviron using the environment variable R_LIBS_USER, instead of defining the library paths in ~/.Rprofile or Rprofile.site. The latter seems to be ignored by R CMD build and R CMD check.
Or you can add Sys.setenv(R_LIBS_USER="/my/r-package/dir/") to ~/.Rprofile.

Resources