2016-08-17 45 views
3

我有一個小表格,我在Rstudio中由knitr生成的pdf文檔中顯示。使用kable編寫的knitr和表格控制科學記數法和格式()

大部分值都是小數,所以科學記數法很好。但是,我有幾個零也顯示在科學記數法中。

有沒有辦法顯示這些只是普通的零?

這裏是一個形象:與kable(data)

+1

你可以嘗試'選項(scipen = 999)'發出你的'kable(數據)之前' –

回答

2

生產

basic table with scientific notation for zeros

該表是這裏的做到這一點的方法之一。一般的想法是,你首先按照你想要的方式格式化數字(小數位數等),然後將零值改爲「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

相關問題