2016-07-27 74 views
1

我有一個包含使用特定字體系列的繪圖的源文件(在knitr中)。我想的警告信息抑制任何特定警告消息的排放

在grid.Call(L_textBounds,as.graphicsAnnot(X $標籤),...:字體 家庭無法在Windows字體數據庫中找到

library(ggplot2) 

ggplot(mtcars, aes(mpg, cyl, label = gear)) + 
    geom_text(family = "helvet") 

我知道我可以抑制腳本options(warn = -1)所有警告消息,我知道如何使用suppressWarnings,我也可以圍繞特定塊在tryCatch

有沒有辦法來suppres只有grid.Call以上的警告整個一個文件?

+0

我還沒有看到這個實施,但我很想被證明是錯誤的。 –

+0

'options(「warning.expression」)'提供線索嗎?我只能用它來完全刪除所有的警告信息。 – Hugh

+0

該選項用於替換更多定製的警告消息。 R對消息的捕獲並不是它的強項(我正在考慮與Python進行比較),但對統計數據來說已經足夠了。 :) –

回答

2

使用

withCallingHandlers({ 
    <your code> 
}, warning=function(w) { 
    if (<your warning>) 
     invokeRestart("muffleWarning") 
}) 

例如,

x = 1 
withCallingHandlers({ 
    warning("oops") 
    warning("my oops ", x) 
    x 
}, warning=function(w) { 
    if (startsWith(conditionMessage(w), "my oops")) 
     invokeRestart("muffleWarning") 
}) 

產生輸出

[1] 1 
Warning message: 
In withCallingHandlers({ : oops 
> 

的限制是該conditionMessage可被轉換成另一種語言(特別是如果從基函數),以便文本不會被可靠地識別。

請參閱Selective suppressWarnings() that filters by regular expression