简体   繁体   English

在 R 中禁止自动输出到控制台

[英]Suppress automatic output to console in R

The function callmultmoments computes moments of the normal distribution.函数callmultmoments计算正态分布的矩。 The function automatically prints "Sum of powers is odd. Moment is 0."该函数会自动打印"Sum of powers is odd. Moment is 0." if the sume of the powers is odd.如果幂的总和是奇数。 Is there any way to supress that under the condition that the original function should stay untouched.在原始功能应该保持不变的情况下,有什么办法可以抑制它。

Ex:例如:

require(symmoments)
# Compute the moment for the 4-dimensional moment c(1,1,3,4):

m.1134 <- callmultmoments(c(1,1,3,4))

EDIT:编辑:

As described here we can use如此处所述我们可以使用

## Windows
sink("nul") 
...
sink()

## UNIX
sink("/dev/null")    # now suppresses
....                 # do stuff
sink()               # to undo prior suppression, back to normal now

However, I am writing a package so I want it to be platform independent.但是,我正在编写一个包,所以我希望它与平台无关。 Any ideas what to do instead?有什么想法可以代替吗?

The issue is due to the fact that the function has multiple print statements, where stop , warning , or message would have been appropriate so that people can use suppressWarnings or suppressMessages .问题是由于该函数有多个print语句,其中stopwarningmessage是合适的,以便人们可以使用suppressWarnings warningsuppressMessages

You can work arount it using invisible(capture.output()) around your whole assignment (not just the right side).您可以在整个作业中使用invisible(capture.output())解决它(不仅仅是右侧)。

f1 <- function(n, ...){
    print("Random print statement")
    cat("Random cat statement\n")
    rnorm(n = n, ...)
}

f1(2)
#> [1] "Random print statement"
#> Random cat statement
#> [1] -0.1115004 -1.0830523
invisible(capture.output(x <- f1(2)))
x
#> [1]  0.0464493 -0.1453540

See also suppress messages displayed by "print" instead of "message" or "warning" in R .另请参阅抑制 R 中由“打印”而不是“消息”或“警告”显示的消息

This message from callmultmoments can be suppressed by simply avoiding a moment that is not even.可以通过简单地避免不均匀的时刻来抑制来自 callmultmoments 的这条消息。 Any odd central moment, such as c(1,1,3,4) as in your example will have an expected value of 0 mathematically.任何奇数中心矩,例如在您的示例中的c(1,1,3,4)在数学上的预期值为 0。 That is, the expected value of a CENTRAL moment such as E[X^1 Y^1 Z^3 W^4] , where the sum of powers, such as 1+1+3+4, is odd is automatically 0.也就是说,像E[X^1 Y^1 Z^3 W^4]这样的 CENTRAL 矩的期望值,其中幂的总和,例如 1+1+3+4,是奇数,自动为 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM