格式化数字时意外的 xtable 输出(在 html 中)

Unexpected xtable output (in html) when formatting numbers

在下面的代码中,当我启用 prettyNum(formatC... 命令时,我得到了您在图片中看到的奇怪输出。该代码适用于 R 3.1.1。输出格式为pdf时没有问题。

---
title: "Untitled"
output: html_document
---

Create test data.

```{r}
library(xtable)

my_tab <- structure(list(Category = c("Categ 1", "Categ 1", "Categ 1", 
"Categ 1", "Categ 1", "Categ 2", "Categ 3", "Categ 3", "Categ 4", 
"Categ 4"), Customer = c("512", "541", "579", "635", 
"705", "726", "O33", "O54", "10004", "10012"), Ammount = c(192.65, 
1046.62, 5053.74, 10950.59, 101.89, 48.99, 2.56, 1.62, 728.63, 
846.7)), row.names = c(NA, 10L), class = "data.frame")

# my_tab[,3] <-  prettyNum(formatC(my_tab[,3], format='f', digits=2), big.mark = ".", decimal.mark = ",")

```

Print table:

```{r, results='asis', echo=FALSE}
 print(xtable(my_tab , align="ll|rr",digits=2), type="html", include.rownames = FALSE, 
               html.table.attributes='class="table table-striped table-hover"')
```

R version 3.2.0 (2015-04-16)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=Greek_Greece.1253  LC_CTYPE=Greek_Greece.1253    LC_MONETARY=Greek_Greece.1253 LC_NUMERIC=C                  LC_TIME=Greek_Greece.1253    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base   

other attached packages:
[1] xtable_1.7-4  

loaded via a namespace (and not attached):
[1] htmltools_0.2.6 tools_3.2.0     yaml_2.1.13     rmarkdown_0.7   digest_0.6.8

我认为 xtable 在前导空格方面存在一些问题。

您可以使用

删除空格
my_tab[,3] <- trimws( prettyNum(formatC(my_tab[,3], format='f', digits=2), big.mark = ".", decimal.mark = ",")) 

或将数字保留在数据中(不将它们转换为字符)并通过 xtable.print

中的 format.args 参数格式化它们
print(xtable(my_tab , align="llrr"), type="html", include.rownames = FALSE, 
  html.table.attributes='class="table table-striped table-hover"',
  format.args = list(big.mark = ".", decimal.mark = ","))