如何在R包帮助文件示例中有条件使用Suggests中的包?
Hey there, let’s get this sorted out—you’re totally right that the direct library() calls in your help file examples are the culprit here. CRAN enforces strict rules for Suggested packages: they can’t be assumed to be present, so every piece of code (including documentation examples) that uses them needs conditional checks.
Here’s how to fix this step by step:
Replace direct
library()calls with conditional checks
Instead of loading the Suggested package outright, userequireNamespace()to verify it’s installed first, then call functions using the::operator (no need to load the entire package). This keeps your examples safe when the Suggested package is missing. For example:# Check if the suggested package is available if (!requireNamespace("your_suggested_pkg", quietly = TRUE)) { stop("'your_suggested_pkg' is required to run this example. Please install it from CRAN.", call. = FALSE) } # Use the package's function without loading it your_suggested_pkg::target_function()If you prefer to use your existing
check.packages()function (since it already handles error throwing), that works too—just call it before using the package’s functions in the example:check.packages("your_suggested_pkg") your_suggested_pkg::target_function()Optional: Use
\dontrun{}for non-essential examples (if needed)
If some examples are purely demonstrative and don’t need to run during CRAN’s checks, you can wrap them in\dontrun{}, but this is less ideal than conditional checks. Users who have the Suggested package installed won’t be able to run those examples directly from the help page, so conditional checks are the better practice.
The key idea here is to make sure your package never tries to use a Suggested package without first confirming it’s installed. Your main code already does this with check.packages(), so aligning your help examples with the same logic will satisfy CRAN’s requirements and prevent archiving.
内容的提问来源于stack exchange,提问作者Noah

