簡體   English   中英

pander 小數點后的位數

[英]pander number of digits after decimal point

我正在嘗試使用 .rmd 文件中的 pander 將表格輸出為 pdf 格式,小數點后有 2 位數字,但使用以下 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 )而產生一些間接影響)。 這里的主要問題是nsmall不允許你設置format()nsmall參數,它會設置

以非科學格式格式化實數/復數時小數點右側的最小位數。 允許的值為 0 <= nsmall <= 20。

但由於 pander 僅將數值提供給format()您可以通過將值as.character()as.character()來簡單地解決此問題:

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
------------------------------------

?panderOptions頁面指​​出,'digits' 被傳遞到format ,在那里它被解釋為“有效數字”的數量。 有效數字實際上與小數位數幾乎沒有關系。 十進制值 0.000041 中可以有 2 個有效數字。 您可以看到參數對format() -ed 值的影響:

> format(c( 10000.41,  9999.68, 10000.64 ), digits=2)
[1] "10000" "10000" "10001"

您確實希望將“圓形”選項保留為 2。

問題是digits部分。 您必須將數字增加到小數點前后的最大位數。 您最大的數字(關於數字)在小數點前有 5 位數字,在小數點后有 2 位數字(例如 10000.41)。 因此,您需要將數字設置為 7 並將(離開)舍入為 2:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM