build vignette with devtools::install_local - global variables created in one vignette is available in another

Viewed 152

I have a R package with two markdown vignettes.

In the first vignette called "aaa_1", I define a variable var. In the second vignette called "aaa_2" I use the variable created in the first vignette.

When installing the package with:

devtools::install_local("package", build_vignette = TRUE)

it builds the two vignettes, but how is this possible? Why is the variable var avilable to the second vignette? I was expecting the install to fail, because var is not defined in "aaa_2". Are the variables, defined in a vignette, global variables?

And can I do something to avoid this?

This is only a problem because the vignettes are created in alphabetical order. If the names had been in the opposite order, the install would have failed. The two vignettes looks like this:

"aaa_1":


title: "aaa_1"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteEngine{knitr::knitr}
  %\VignetteIndexEntry{aaa_1}
  %\usepackage[UTF-8]{inputenc}
---


```{r}
a = data.frame(
  "hello" = c("hi","hi", "hi"),
  "goodbye" =  c("bye", "bye", "bye")
)

print(a)

```

"aaa_2":


title: "aaa_2"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteEngine{knitr::knitr}
  %\VignetteIndexEntry{aaa_2}
  %\usepackage[UTF-8]{inputenc}
---

```{r}
print(a)

a2 <- a[, "hello"]
```
1 Answers

I get the same result as you using the standard R CMD build and R CMD INSTALL, so I'd guess devtools is using the standard tools under the hood, or trying to emulate them. I agree with you, this shouldn't happen: vignettes should be self-contained.

If I run R CMD check or devtools::check() it does issue a warning:

> checking re-building of vignette outputs ... WARNING
  Error(s) in re-building vignettes:
    ...
  --- re-building ‘Untitled2.Rmd’ using rmarkdown
  --- finished re-building ‘Untitled2.Rmd’
  
  --- re-building ‘aaa_1.Rmd’ using knitr
  --- finished re-building ‘aaa_1.Rmd’
  
  --- re-building ‘aaa_2.Rmd’ using knitr
  Quitting from lines 11-14 (aaa_2.Rmd) 
  Error: processing vignette 'aaa_2.Rmd' failed with diagnostics:
  object 'a' not found
  --- failed re-building ‘aaa_2.Rmd’
  
  SUMMARY: processing the following file failed:
    ‘aaa_2.Rmd’
  
  Error: Vignette re-building failed.
  Execution halted

so I guess that answers your question: to avoid this, make sure your package passes checks with no warnings or errors.

Related