2

我想在编写 html 或 pdf 时使用自定义类来很好地使用 pandoc.tables(我正在使用 pander)显示大量数字。

由于这个 SO question ,我找到了一种在控制台中很好地打印的方法。

在此示例中,打印 x 返回 6M 75M 743.5M 0.3M 4.3M:

print.million <- function(x, ...) {
    x <- paste0(round(x / 1e6, 1), "M")
    NextMethod(x, quote = FALSE, ...)
}
x <- c(6e+06, 75000400, 743450000, 340000, 4300000)
class(x) <- "million"
x

但是这种格式会随着 pandoc.table 消失:显示原始的、未格式化的值。我也尝试过自定义格式(上述 SO 问题的答案):

format.million <- function(x,...)paste0(round(unclass(x) / 1e6, 1), "M")
as.data.frame.million <- base:::as.data.frame.factor

但没有成功。

有没有办法使这项工作?我对 pander 以外的解决方案持开放态度,但 kable 似乎与我的 R 版本(R 版本 3.2.3)不兼容。

4

1 回答 1

0

print.million方法对 没有影响pander,这是一个不同的 S3 方法——所以你必须在pander.million这里定义,例如:

> x <- c(6e+06, 75000400, 743450000, 340000, 4300000)
> pander(x)
_6000000_, _75000400_, _743450000_, _340000_ and _4300000_

> pander.million <- function(x, ...) pander(paste0(round(x / 1e6, 1), "M"))
> class(x) <- 'million'
> pander(x)
_6M_, _75M_, _743.5M_, _0.3M_ and _4.3M_

但是要在带有 的表中使用它pandoc.table,我不确定您如何million为列设置类。你能想出一个可重现的例子吗?

但是例如你可以预处理你的data.frame

> x <- as.numeric(x)
> df <- data.frame(millions = x, billions = x * 1e3, text = 'foobar')
> numbers <- names(df)[sapply(df, is.numeric)]
> df[numbers] <- apply(df[, numbers, drop = FALSE], 1,
+                      function(x) paste0(round(x / 1e6, 1), "M"))
> pander(df, justify = 'right')

----------------------------
  millions   billions   text
---------- ---------- ------
        6M    743450M foobar

     6000M       0.3M foobar

       75M       340M foobar

  75000.4M       4.3M foobar

    743.5M      4300M foobar
----------------------------
于 2016-03-08T00:18:19.713 回答