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

标签 r knitr scientific-notation

我在 Rstudio 中的 knitr 生成的 pdf 文档中显示了一个小表格。

大多数值都是小数,因此可以使用科学记数法。但是,我有一些零也以科学记数法显示。

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

这是一张图片:

basic table with scientific notation for zeros

表格是用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))
```

enter image description here

关于r - 使用 knitr 控制科学记数法和零值格式,使用 kable() 生成表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39005533/

相关文章:

r - 如何从 Rstudio ioslides 演示文稿中删除标题幻灯片

r - R中的百分比格式表

c# - 科学计数法 - .NET 中的错误?

r - 使用 metafor 包将科学记数法中的标签添加到森林图中

c - printf %e 科学记数法在 C 中给出错误的值

r - 使用cairo在轴标题中使用表达式和unicode保存ggplot

regex - 如何最有效地将 "01 Jan 2014"的字符串转换为 POSIXct,即 "2014-01-01"yyyy-mm-dd

r - 使用dplyr重命名列

r - 在 R 编程中对数据帧中的列中的值进行计数

r-markdown - Rmarkdown - 打印对象列表而不显示那些讨厌的 [[indices]]