gpt4 book ai didi

r - pander 小数点后的位数

转载 作者:行者123 更新时间:2023-12-04 09:21:52 25 4
gpt4 key购买 nike

我正在尝试使用 .rmd 文件中的 pander 将表格输出为小数点后有 2 位数字的 pdf,但我使用以下 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 参数,这将设置

the minimum number of digits to the right of the decimal point in formatting real/complex numbers in non-scientific formats. Allowed values are 0 <= nsmall <= 20.

但由于 pander 仅将数值提供给 format(),您可以通过将值 as.character() 提供给 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
------------------------------------

关于r - pander 小数点后的位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36777740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com