使用 knitr 控制科学记数法和零值格式,使用 kable() 生成表格

Control scientific notation and format of zero values with knitr and tables produced with kable()

我有一个小 table 显示在 Rstudio 中 knitr 生成的 pdf 文档中。

大多数值都是小数,所以科学记数法就可以了。但是,我有一些零也以科学计数法显示。

有没有办法将它们显示为常规零?

这是一张图片:

table 是用 kable(data)

生成的

这是一种方法。一般的想法是首先按照您想要的方式格式化数字(小数位数等),然后将零更改为“0”。

---
title: "Untitled"
author: "Author"
date: "August 17, 2016"
output:
  pdf_document
---

```{r setup, include=FALSE}
library(knitr)
```

```{r}
# Some data
df = mtcars[1:5,c(1,3:4)]/1e7
rownames(df) = NULL

# Set a few values to zero
df[2:3,2] = 0
df[c(1,3),1] = 0

# Look at the starting data
kable(df)
```

```{r}
## Reformat table so that zeros are rendered as "0"

# First, format data so that every number is rendered with two decimal places
df = lapply(df, format, digits=3)

# If a value is zero, change string representation to "0" instead of "0.00e+00"
df = sapply(df, function(i) ifelse(as.numeric(i) == 0, "0", i))

kable(df, align=rep('r',3))
```