suppressMessages 在 R 中带有返回而不是打印?

suppressMessages with a return instead of a print in R?

提问人:dfife 提问时间:10/4/2019 最后编辑:dfife 更新时间:9/10/2021 访问量:1403

问:

我有一个包,其中包含一堆生成 ggplot2 对象的函数。最近,ggplot2 添加了一个更新,该更新给出了一条消息:

`geom_smooth()` using method = 'loess' and formula 'y ~ x'

我知道为什么 ggplot2 这么说,但我不需要每次运行情节时都听到它(这让我的用户感到困惑,因为他们认为他们做错了什么)。我知道我可以通过包装 print 语句来抑制消息,但我不想要绘图,我想要它。如果我这样做,它就会显示情节,即使我不想显示它。suppressMessagesprintreturnprint

有什么想法吗?这是一个最低限度的工作示例。

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)
r ggplot2 抑制消息

评论

0赞 JBGruber 10/4/2019
也许设置而不是默认值?method = 'loess'
0赞 dfife 10/4/2019
消息只是更改为更短的内容。
0赞 iod 10/4/2019
仅当绘制绘图时才会生成该消息,因此您可以环绕对 的调用。值得注意的是 - 如果您分配了结果(即,它不是隐式打印),则不会出现警告suppressMessagesff
0赞 dfife 10/5/2019
抱歉,即使 se=F 时使用 method=“loess”,该消息仍然存在。

答:

5赞 JBGruber 10/4/2019 #1

您可以只设置 ,而不是 ,这是默认值: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

创建于 2019-10-04 由 reprex 软件包 (v0.3.0)

我在这里没有看到一条消息,甚至没有一条简短的消息。

另一种选择是定义自定义打印函数,并为输出对象提供不同的类:

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))
}

这将在打印返回的对象时禁止显示消息。由于这会添加一个类而不是覆盖旧类,因此您仍然可以毫无问题地添加参数。不过,我想说的是,第一种选择应该是更好的选择。+

评论

0赞 iod 10/4/2019
这种新方法是一个绝妙的解决方案!
0赞 jarauh 9/10/2021
也许这取决于 ggplot2 的版本,但当前的 ggplot2 仍然打印一条消息:“使用公式 'y ~ x'”。如果您不想收到此消息,则需要传递参数。geom_smooth()fromula = y ~ x
1赞 jarauh 9/10/2021 #2

根据源代码,并且将打印消息,除非 和 都作为参数给出(此外,不应该是)。如果您使用 ,那么您很可能想要 .因此,以下内容应该静默工作:stat_smoothgeom_smoothmethodformulamethod"auto"method = "loess"formula = y ~ x

f = function(y,x,data){
    ggplot(data, aes_string(x,y)) + geom_point() +
        geom_smooth(se=F, method = "loess", formula = y ~ x)
}
data(iris)
head(iris)
f("Sepal.Length", "Sepal.Width", iris)

(我还删除了额外的赋值和显式的 return 语句,但这是一个品味问题。