warning() 函式

R 防禦式程式設計

Dr. Colin Gillespie

Jumping Rivers

警告訊息

warning() 函式

warning("You have been warned!")
# Warning message:
# You have been warned!
  • 表示可能有問題發生
  • R 會繼續執行(不同於錯誤)
  • 會加上「Warning message:」 前綴
R 防禦式程式設計

抑制警告

和訊息類似,你可以用下列方式抑制警告:

  • suppressWarnings()

這幾乎從來不是好主意

  • 應該修正根本問題!
R 防禦式程式設計

何時該用警告?

攝影:Austin Chan

R 防禦式程式設計

警告的好例子

假設我們要對下列資料做迴歸:

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

所以 x2 = x1 + 1。

當我們擬合多元線性迴歸模型時

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
R 防禦式程式設計

換你試試

R 防禦式程式設計

Preparing Video For Download...