Alternatives to `\dontrun{}` for examples that error on pkgdown sites or whose output is hardly readable

What's the recommend approach to not run examples only on the pkgdown site or examples that produce an output that's barely readable/intelligible for users?

People at CRAN complain about the use of \dontrun{} in example 1 and example 2.

Example 1 prints a (very) long markdown image link which is of no use for users. Example 2 can run properly locally but won't work on the pkgdown site because of withr::local_tempfile(). Instead, the example will throw a cannot open the connection error as shown here.

Would wrapping example 2 in

if (interactive()) {
  ...
}

prevent the example from being run on the pkgdown site?

Yes, if (interactive()) { ... } will not run on pkgdown by default, at least not with pkgdown::build_site().

Another alternative is the @examplesIf tag if you are using roxygen2. With that you can write the exact condition you want the example to run.

EDIT: there are about a thousand examples for the @examplesIf tag on CRAN: https://github.com/search?q=org%3Acran%20%40examplesIf&type=code
E.g. to only run the examples when not on CRAN, always except for R CMD check, when the computer is online, when some packages are installed, only on Windows, etc.

The good thing about it is that the end user will just see the example code, without any boilerplate at all, but you can still finetune when the examples should be be running, and when they should not.

2 Likes

I, unfortunately, recommend:

if (FALSE) {
  ...
}

It is the only thing that is likely to avoid running in multiple environments and survive policy changes on things like dontrun.

Obviously, if (FALSE) { ... } is not great because then your examples are not tested at all, but I would write even that with @examplesIf, so the user does not see the confusing boilerplate.

Well in that case, I'd say have different directory of tests, examples, and vignettes you don't want CRAN to see. And then, don't push that directory to CRAN. The "here it is, but please don't look" convention has been broken before.

Great! I knew about @examplesIf but wasn't sure about the benefits of using it. So I'll use @examplesIf interactive() for example 2 and I guess I'll simply instantiate the class without outputting anything for example 1.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.