在R中以相同的向量打印科学和标准符号

  • 本文关键字:打印 符号 标准 向量
  • 更新时间 :
  • 英文 :


我想让R打印一个混合了标准和科学符号的向量。

为什么?这样更容易阅读。

具体来说,我有一个向量,它的值在0和1之间有很大的差异;有些数量级从10^-1到10^-16,我希望那些数量级为10^-1或-2的以标准格式打印,而那些大得多的以科学格式打印。

目前我只能强制R执行1或其他操作。

> rrr <- c(0.12, 0.01333, 0.0000000000000003856)
> rrr
[1] 1.200e-01 1.333e-02 3.856e-16

> options(scipen = 12)
> rrr
[1] 0.1199999999999999956 0.0133299999999999998 0.0000000000000003856

因此,scipen似乎适用于整个向量,而不是每个元素。同样地,将例如options(digits = 2)更改为将最小的数字舍入为0.00000000000000039

我想看的是

> rrr
[1] 0.12 0.013333 3.856e-16

想法吗?

谢谢,你们都是传奇!

[另外,我不理解scipen = 12时的非舍入行为,但这是另一个问题…]

这肯定是一个hack,并且它是不完整的引导:"很棒"的方式是让这个函数像大多数基于s3的函数一样工作,并且实际上在"打印"数字对象时被调用。

而且,它还远远没有完成。在这种情况下,它假设一个向量,而不考虑控制台宽度、等间距等因素。

但这是一个开始("play"的一个例子),展示了一个"可能"如何处理强迫症,比如:-)

options(scipen2 = 3)
print.numeric <- function(x, ...) {
  scipen2 <- getOption("scipen2", default = 3)
  cat(c(ifelse(abs(log(x, 10L)) >= scipen2,
               format(x, digits = 5, scientific = TRUE),
               format(x, digits = 1, scientific = FALSE)),
        "n"))
}
print(c(101, NA, pi / 100, pi / 10000, 1/100, pi * 10000))
#   101.0000 NA     0.0314 3.1416e-04     0.0100 3.1416e+04 

我不建议在生产环境中使用。我甚至不建议在开发中使用它,除非您乐于面对破损、糟糕的格式等问题。也许它会激发一些想法和/或对话。(但除了讨论好奇心之外,它真的不适合做任何事情。)

让steve的评论更进一步:

rrr <- c(0.12, 0.01333, 0.0000000000000003856)
#the foom calculates the order of magnitude of the number. Division by 1000 set the
# number of digits to preserve - 3 more than the order of magnitude
foom <- function(x) {
  -round(log10(abs(x/1000)),0)
}
#round by foom and print as charecter
sapply(round(rrr,foom(rrr)), function(x) as.character(x))
#[1] "0.12"     "0.01333"  "3.86e-16"

最新更新