禁止自动输出到R中的控制台 [英] Suppress automatic output to console in R

查看:93
本文介绍了禁止自动输出到R中的控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数callmultmoments计算正态分布的矩. 如果幂的和为奇数,该功能将自动打印"Sum of powers is odd. Moment is 0.".在保持原始功能不变的情况下,有什么办法可以抑制这种情况.

The function callmultmoments computes moments of the normal distribution. The function automatically prints "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.

例如:

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

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

此处所述,我们可以使用

## 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?

推荐答案

问题是由于该函数具有多个print语句,其中stopwarningmessage本来应该存在的以便人们可以使用suppressWarningssuppressMessages.

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.

您可以使用invisible(capture.output()) 围绕整个作业(不仅仅是右侧)来实现它.

You can work arount it using invisible(capture.output()) around your whole assignment (not just the right side).

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

另请参见禁止显示打印"而不是消息"或警告"在R 中.

这篇关于禁止自动输出到R中的控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆