dfi*_*ife 4 r ggplot2 suppressmessage
我有一个包,里面有一堆生成 ggplot2 对象的函数。最近,ggplot2 添加了一个更新,给出了一条消息:
`geom_smooth()` using method = 'loess' and formula 'y ~ x'
Run Code Online (Sandbox Code Playgroud)
我知道 ggplot2 为什么这么说,但我不需要每次运行绘图时都听到它(这让我的用户感到困惑,因为他们认为他们做错了什么)。我知道我可以通过包装一个打印语句来抑制消息,suppressMessages但我不想print情节,我想要return它。如果我是print它,它会显示情节,即使我不想显示它。
有任何想法吗?这是一个最小的工作示例。
f = function(y,x,data){
p = ggplot(data, aes_string(x,y)) + geom_point() + geom_smooth(se=F)
#suppressMessages(return(p)) ### doesn't work
suppressMessages(print(p)) ### works, but I don't want to PRINT it
}
data(iris)
head(iris)
f("Sepal.Length", "Sepal.Width", iris)
Run Code Online (Sandbox Code Playgroud)
您可以只设置method = 'loess'而不是method = 'auto',这是默认值:
library(ggplot2)
f = function(y,x,data){
p = ggplot(data, aes_string(x,y)) + geom_point() + geom_smooth(method = "loess")
return(p)
}
data(iris)
gg <- f("Sepal.Length", "Sepal.Width", iris)
gg
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2019 年 10 月 4 日创建
我在这里没有看到任何消息,甚至没有看到一条短消息。
另一种选择是定义自定义打印函数并为您的输出对象提供不同的类:
f = function(y,x,data){
p = ggplot(data, aes_string(x,y)) + geom_point() + geom_smooth()
class(p) <- c("gg_silent", class(p))
return(p)
}
print.gg_silent <- function(gg) {
suppressMessages(ggplot2:::print.ggplot(gg))
}
Run Code Online (Sandbox Code Playgroud)
这将在打印返回的对象时抑制消息。由于这会添加一个类而不是覆盖旧的类,因此您仍然可以+毫无问题地添加参数。我仍然会说第一个选择应该是更好的选择。