本文介绍了pander 小数点后的位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 .rmd 文件中使用 pander 将表格输出为 pdf 格式,小数点后有 2 位数字,但使用以下 rmd 没有得到任何数字:

I am trying to output a table using pander in a .rmd file as a pdf with 2 digits following the decimal point, but I get no digits using the following rmd:

---
title: "Long table test"
output: pdf_document
---

Here is a table:

```{r setup}
library (data.table)
library (pander)

set.seed(1984)
longString <- "description string"
dt <- data.table(id=c(1:3),description=rep(longString,3),value=rnorm(3,mean=10000,sd=1))
```

```{r pander-table}
panderOptions('round',2)
panderOptions('digits',2)
panderOptions('keep.trailing.zeros',TRUE)
pander(dt, split.cell = 80, split.table = Inf)
```

结果

-------------------------------
 id     description      value
---- ------------------ -------
 1   description string  10000

 2   description string  10000

 3   description string  10001
-------------------------------

想看

----------------------------------
 id     description      value
---- ------------------ ----------
 1   description string  10000.41

 2   description string   9999.68

 3   description string  10000.64
----------------------------------

推荐答案

设置 round 对数字位数没有任何直接影响(尽管由于潜在地使数字变得无关紧要而产生了一些间接影响(0)).这里的主要问题是 pander 不允许你设置 format()nsmall 参数,它会设置

Setting round doesn't have any direct influence on the number of digits (though some indirect influence due to potentially rendering digits insignificant (0)). The main problem here is pander doesn't allow you to set the nsmall parameter of format() which would set

以非科学格式格式化实数/复数时小数点右侧的最小位数.允许的值为 0

但是由于pander只将数值提供给format(),你可以简单地通过将值as.character()提供给pander来解决这个问题:

But since pander only feeds numeric values to format() you can simply work around this by feeding the values as.character() to pander:

library (data.table)
library(magrittr)
library (pander)

set.seed(1984)
longString <- "description string"
dt <- data.table(id = c(1:3),
                 description = rep(longString, 3),
                 value = rnorm(3, mean = 10000, sd = 1))

pander(
  x = dt %>% mutate(value = value %>% round(2) %>% as.character()),
  split.cell = 80,
  split.table = Inf,
  justify = "ccr"
)

导致:

------------------------------------
 id      description           value
---- -------------------- ----------
 1    description string    10000.41

 2    description string     9999.68

 3    description string    10000.64
------------------------------------

这篇关于pander 小数点后的位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:56