设置打印的默认小数位数

Buc*_*yOH 7 r decimal

我正在运行代码来生成输出,我希望所有输出都打印1个小数位.但是代码使用了我一般使用的函数,我不想在这些函数中指定打印输出是四舍五入的.

这个问题的答案格式化R中的小数位数建议使用options(digits=2)round(x, digits=2).

第一个选项是一般设置,非常适合舍入1.234到,1.2但会打印12.34512

如果放在函数中但第二个选项可以工作,但我不想触摸它们.如何设置这一般?

Mat*_*rde 8

你可以这样做:

print <- function(x, ...) {
    if (is.numeric(x)) base::print(round(x, digits=2), ...) 
    else base::print(x, ...)
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*nes 5

我喜欢formatC打印具有指定小数位数的数字.这样,1应该始终打印为"1.0"when digits = 1format = "f".您可以为类数字对象创建S3打印方法,如下所示:

print.numeric<-function(x, digits = 1) formatC(x, digits = digits, format = "f")

print(1)
# [1] "1.0"

print(12.4)
# [1] "12.4"

print(c(1,4,6.987))
# [1] "1.0" "4.0" "7.0"

print(c(1,4,6.987), digits = 3)
# [1] "1.000" "4.000" "6.987"
Run Code Online (Sandbox Code Playgroud)