格式化数字时出现意外的xtable输出(以html格式)

时间:2015-06-19 13:41:10

标签: r knitr r-markdown xtable

在下面的代码中,当我启用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"')
```

enter image description here

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

1 个答案:

答案 0 :(得分:2)

我认为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 = ","))