使用 return 而不是 R 中的打印来抑制消息?

suppressMessages with a return instead of a print in R?

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

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

我知道为什么 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)

您可以只设置 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

reprex package (v0.3.0)

于 2019-10-04 创建

我在这里没有看到任何消息,连一条短消息都没有。

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

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

这将在打印返回的对象时抑制消息。由于这会添加一个 class 而不是覆盖旧的,您仍然可以毫无问题地添加带有 + 的参数。我还是会说第一个选项应该更好。

根据 source codestat_smoothgeom_smooth 将打印消息,除非 methodformula 都作为参数给出(此外,method 不应该是 "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 语句,但这是个人喜好问题。)