warning
warning(..., call. = TRUE, immediate. = FALSE, noBreaks. = FALSE, domain = NULL) warning() signals a warning condition in R, printing a message without halting execution. It sits between silent success and fatal error, you know something is off, but the computation keeps going. This makes it the right tool for non-fatal problems: unusual values, deprecated patterns, or conditions that warrant attention but don’t justify stopping.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
... | any | , | Zero or more objects coerced to character and pasted together. Can also be a single condition object (see Gotchas). |
call. | logical | TRUE | If TRUE, the call that triggered warning() prints alongside the message. |
immediate. | logical | FALSE | If TRUE, prints the warning immediately even when getOption("warn") <= 0. |
noBreaks. | logical | FALSE | If TRUE, the message avoids line breaks in formatted output. |
domain | character | NULL | For message translation. Pass NULL to skip translation lookup. |
Basic usage
Give warning() a character message and it prints immediately:
warning("something is not quite right")
# Warning message:
# In warning("something is not quite right") :
# something is not quite right
Multiple arguments paste together without separators, so include spaces explicitly. R calls paste0(..., collapse = "") under the hood, joining all arguments into a single string with no gaps. This behaviour mirrors stop() and message(), making the three condition-signalling functions consistent in how they assemble multi-part messages. If you forget the leading space in " Found", the output reads Found1 missing values with no separation between the literal and computed parts.
x <- c(3.14, NA, 2.71)
warning("Found ", sum(is.na(x)), " missing values in input")
# Warning: Found 1 missing values in input
Controlling call display
By default, call. = TRUE and the triggering call prints. The call display includes the function name and argument values that produced the warning, giving a breadcrumb trail back to the source. In a function context this gets noisy:
check_value <- function(x) {
if (x < 0) warning("negative value received")
x
}
check_value(-5)
# Warning in check_value(-5) : negative value received
Set call. = FALSE to suppress the calling context. When call. is FALSE, only the warning message text appears, omitting the function name and argument trace. This keeps package output tidy for end users who should not see internal implementation details. The tradeoff is losing the call site information that speeds up debugging during development, so consider exposing a verbose parameter that conditionally toggles call display based on context.
check_value <- function(x) {
if (x < 0) warning("negative value received", call. = FALSE)
x
}
check_value(-5)
# Warning: negative value received
In package code, call. = FALSE is usually cleaner. In interactive exploration, call. = TRUE helps you locate where the warning originated.
The warn option
R’s warning behavior is controlled globally by getOption("warn"). Understanding the levels helps you debug warning-heavy code:
| Value | Behavior |
|---|---|
-1 | Warnings are ignored completely |
0 (default) | Warnings accumulate in last.warning and print after the top-level function finishes |
1 | Warnings print immediately as they occur |
2 or higher | Warnings are converted to errors and halt execution |
The default (warn = 0) batches warnings, this keeps interactive output clean but can make warnings feel disconnected from their source:
options(warn = 1)
warning("first warning")
# Warning: first warning
options(warn = 2)
warning("this becomes an error")
# Error: (converted from warning) this becomes an error
Reset to default after testing. Leaving warn = 2 active turns all subsequent warnings into errors, which can break scripts that depend on non-fatal diagnostics. The idiom old <- options(warn = 2); on.exit(options(old)) restores the previous setting automatically when the current function exits, avoiding side effects that leak into the global session and surprise users of downstream code.
options(warn = 0)
Inspecting stored warnings
When warn = 0, warnings accumulate in last.warning and print only when control returns to the top level. This delayed printing means warnings from deeply nested function calls appear together at the end, which helps readability but can obscure which call triggered which warning. Calling warnings() explicitly forces immediate display of the accumulated list without waiting for the top-level return, giving you a snapshot of all pending warnings at any point in execution.
options(warn = 0)
warning("first")
warning("second")
warnings()
# Warning messages:
# 1: first
# 2: second
last.warning is a named list of condition objects. You can inspect it directly. Each element is a simpleWarning object with a message and call component, matching the structure returned by simpleWarning(). This means you can programmatically extract warning text with sapply(last.warning, conditionMessage) to build a character vector for logging or filtering, without parsing the printed output format.
last.warning
# $message
# [1] "first"
#
# $message
# [1] "second"
To clear stored warnings without printing them, assign NULL to last.warning. This assignment directly modifies the base namespace environment, so it affects the global warning state immediately. Functions that call suppressWarnings() internally do not add entries to last.warning, but warnings generated outside such calls accumulate until cleared. If you are chaining multiple operations that each may warn, clearing between steps keeps the buffer from filling with stale messages from earlier stages.
last.warning <- NULL
Suppressing warnings
Use suppressWarnings() to evaluate an expression with all warnings silenced. The function wraps its argument in withCallingHandlers() with a handler that catches every warning and calls invokeRestart("muffleWarning"), preventing the warning from printing or accumulating in last.warning. The return value is the expression result, not the warnings, so you can assign the output directly as if no warning had occurred.
# NaN produced, but we handle it
result <- suppressWarnings(log(-1:1))
result
# [1] NaN 0.000000
suppressWarnings() returns the value of the expression, not the warnings. It’s useful when you know a particular operation produces expected warnings and you want to keep output clean.
Custom handlers with tryCatch()
For fine-grained control, tryCatch() intercepts warnings with a warning handler. Inside the handler, invokeRestart("muffleWarning") stops the warning from printing:
tryCatch(
{
warning("this gets caught")
42
},
warning = function(w) {
message("Caught warning: ", w$message)
invokeRestart("muffleWarning")
}
)
# Caught warning: this gets caught
# [1] 42
Without invokeRestart("muffleWarning"), the warning handler runs but the warning still prints after the handler returns. The handler can inspect and log the warning condition, but unless it explicitly muffles the restart, R’s default behaviour kicks in and the warning message reaches the user. This two-phase design separates interception from suppression, giving you the option to record warnings while still letting them surface normally.
Gotchas
Condition objects ignore other arguments. When you pass a condition object as the sole argument to warning(), all other parameters are silently ignored:
# Call display is ignored here
warning(simpleWarning("message", quote(sum(x))), call. = FALSE)
Warning truncation. R truncates warning messages to getOption("warning.length") characters (default 1000). Long messages end with [... truncated].
Warnings persist across function calls. With warn = 0, last.warning accumulates across nested calls. If a loop calls code that generates warnings, all of them print when the loop completes. Clear last.warning explicitly if you need a clean slate.
immediate. = TRUE forces immediate printing. Even when warn = 0, immediate. = TRUE causes the warning to print right away. This is useful for debugging inside functions where you want to see a warning without changing global options.
See also
stop(), signal a fatal error that halts executiontryCatch(), catch and handle warnings, errors, and other conditionswithCallingHandlers(), establish local handlers without muffling- Error handling in R — patterns for managing warnings and errors in practice