使用knitr和kable()控制零值的科学计数法和格式

3

我有一个小表格,我正在使用Rstudio中的knitr生成的pdf文档中显示它。

大多数值都是小数字,因此科学计数法是可以接受的。但是,我有一些零也以科学计数法显示。

有没有办法将它们显示为普通的零?

这里是一张图片:

basic table with scientific notation for zeros

该表格是用kable(data)生成的。


1
在执行 kable(data) 命令之前,您可以尝试使用 options(scipen=999) - renato vitolo
1个回答

2

以下是一种方法。总的思路是首先按照您想要的方式格式化数字(小数位数等),然后将值为零的数字更改为“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))
```

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接