The warning() function

Defensive R Programming

Dr. Colin Gillespie

Jumping Rivers

The warning message

The warning() function

warning("You have been warned!")
# Warning message:
# You have been warned!
  • signals that something may have gone wrong
  • R continues (unlike an error)
  • "Warning message:" is (pre) appended
Defensive R Programming

Suppress Warnings

Similar to messages, you can suppress warnings via

  • suppressWarnings()`

This is almost never a good idea

  • Fix the underlying problem!
Defensive R Programming

When should you use a warning?

Photo by Austin Chan

Defensive R Programming

A good use of warning

Suppose we're performing regression on

d = data.frame(y = 1:4, x1 = 1:4)
d$x2 = d$x1 + 1

So x2 = x1 + 1

When we fit a multiple linear regression model

m = lm(y ~ x1 + x2, data = d)
summary(m)
# Some output removed 
# Warning message:
# In summary.lm(m) : essentially perfect fit: summary may be unreliable
Defensive R Programming

Your turn

Defensive R Programming

Preparing Video For Download...