简体   繁体   中英

How do I conditionally use R packages in help file examples?

I'm an R package author, and I received a notice form CRAN that my package was going to be archived because the packages in my Suggests need to be used conditionally. In my main code, they are used conditionally; I wrote a check.packages() function that throws an error if the package is not able to be loaded. In the examples in my Help files, though, I simply attach the package with library() , which is likely where I made my mistake. The problem arose because a package I included in Suggests was archived.

My question is how do I conditionally use packages in examples in Help files? I tried using

ifelse{\Sexpr{isTRUE(requireNamespace("pkg"))}}{
#Example with pkg
}{
\dontrun{
#Example with pkg
}}

that is, if the package is loadable, display the example as usual, and if not, wrap \\dontrun{} around it. This worked when I previewed the Help file, but the CRAN check tells me I can't use \\ifelse in examples. If it's important that my examples attach packages in my Suggests, is my only option to wrap \\dontrun around all of them, regardless of whether the package can be loaded?

CRAN were happy with a simple if statement in the vignette of one of my packages :

if (requireNamespace('pkg', quietly = TRUE)) {
  library('pkg')
  # Example with pkg
} else {
  message("'pkg' not available")
}

I could be missing something, but I can't see why this approach shouldn't work in examples too; perhaps you would need to add an unloadNamespace('pkg') after the example to clean up?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM