R语言良好编码实践:message/cat/print/warning/error的使用及R包开发中错误与警告的函数选择
Great question! Let’s break down each of these R functions, their intended uses, best practices, and how to choose the right one for package development.
Let’s start with what each function is designed for, and when (and when not) to use them:
1. print()
- Primary purpose: Displaying the contents of R objects (data frames, vectors, custom S3/S4 objects). It’s the default function called when you type an object name and hit enter in the console.
- Best practices:
- Don’t use it for status updates, warnings, or errors—that’s not what it’s built for.
- It’s fine for quick debugging in interactive sessions, but avoid it in formal package code. Its output depends on the object’s
printmethod, which can be inconsistent across environments.
2. cat()
- Primary purpose: Generating custom-formatted text output (e.g., writing structured reports, logging to files) with full control over line breaks (you need to add
\nmanually) and string concatenation. - Best practices:
- Reserve it for cases where you need precise control over output formatting.
- Never use it for error/warning messages or status notifications—its output isn’t captured by R’s message system, so users can’t suppress it with functions like
suppressMessages().
3. message()
- Primary purpose: Sharing non-critical status updates with users (e.g., "Loaded 100 rows of data", "Processing batch 3 of 5").
- Best practices:
- These are informational messages that don’t halt execution. Users can suppress them with
suppressMessages()if they don’t need the noise. - Use it in packages to keep users informed about what the function is doing, but never for errors or warnings.
- These are informational messages that don’t halt execution. Users can suppress them with
4. warning()
- Primary purpose: Alerting users to potential issues that don’t stop the function from running (e.g., implicit type conversion, minor data inconsistencies that don’t break core functionality).
- Best practices:
- Warnings are "soft errors"—the function continues executing, but users should be aware of a possible problem.
- In packages, use it when the function can still produce a valid result, but there’s a risk the user might not expect the behavior. Users can suppress warnings with
suppressWarnings()or convert them to errors withoptions(warn=2).
5. stop() (Note: R doesn’t have a built-in error() function—this is what you’re referring to)
- Primary purpose: Throwing a fatal error that immediately stops function execution. Use this when the function cannot complete its intended task due to invalid input or a critical failure.
- Best practices:
- Always use this for scenarios where the function can’t proceed (e.g., non-numeric inputs for an addition function).
- Write clear, specific error messages so users know exactly what went wrong (avoid vague phrases like "something went wrong").
When building R packages, follow this hierarchy for messaging:
- Fatal errors: Use
stop()(orrlang::abort()if you’re using the tidyverse ecosystem for structured errors) when the function can’t run at all. This is non-negotiable—don’t let invalid inputs lead to unexpected behavior. - Potential issues: Use
warning()when the function can continue running, but there’s a risk the user might miss an important detail. - Status updates: Use
message()for non-critical progress notifications. - Custom output: Only use
cat()if you need to generate highly formatted text (e.g., writing a report to a file). - Object display: Avoid
print()in package code—reserve it for interactive debugging.
In your function_sum_two_nums example, if a or b isn’t numeric, the addition operation can’t happen at all. This is a fatal error scenario, so you should use stop(). Also, let’s tweak the logic to be more readable:
function_sum_two_nums <- function(a, b){ # Check if inputs are numeric if (!is.numeric(a) || !is.numeric(b)) { stop("Error: Both 'a' and 'b' must be numeric values.") } # Return sum if checks pass a + b }
Testing this:
function_sum_two_nums(1, "2") # Output: Error in function_sum_two_nums(1, "2") : Error: Both 'a' and 'b' must be numeric values.
This makes it clear to users exactly what’s wrong, and stops the function from trying to perform an invalid operation.
内容的提问来源于stack exchange,提问作者CodingBiology

