Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knitr's kable is printing 2.29e-30 as "0"

Tags:

r

knitr

CODE:

# some data
dat <-
  data.frame(
    log2fc = c(0.28, 10.82, 8.54, 5.64, 8.79, 6.46),
    pvalue = c(0.00e+00, 2.29e-30, 7.02e-30, 4.14e-29, 1.86e-28, 1.78e-27)
  )

# observe in markdown format
knitr::kable(dat, format="markdown")

OUTPUT:

| log2fc| pvalue|
|------:|------:|
|   0.28|      0|
|  10.82|      0|
|   8.54|      0|
|   5.64|      0|
|   8.79|      0|
|   6.46|      0|

PROBLEM:

The problem with the output is that, it is rendering the last column pvalue as zeros. But I would want to retain the same format as I see in my dataframe. How do I do that ? I've tried several solutions from various threads but nothing seems to work. Can someone point me to the right direction ?

Please do not suggest me to convert the pvalue column into a character vector. That is a quick and dirty solution that works, but I don't want to do that because:

  1. I don't want to mess around with my dataframe.
  2. I am interested in the reason for why the scientific format of the last column is not being retained while printing it in markdown.
  3. I have many tables each with various columns with scientific format, I am looking for a way that automatically handles this issue.
like image 610
Nikhil Mallela Avatar asked Aug 04 '17 19:08

Nikhil Mallela


1 Answers

kable() calls the base R function round(), which truncates those small values to zero unless you set digits to a really large value. But you can do that, e.g.

knitr::kable(dat, format = "markdown", digits = 32)

which gives

| log2fc|   pvalue|
|------:|--------:|
|   0.28| 0.00e+00|
|  10.82| 2.29e-30|
|   8.54| 7.02e-30|
|   5.64| 4.14e-29|
|   8.79| 1.86e-28|
|   6.46| 1.78e-27|

If you do want the regular rounding in some columns, you can specify multiple values for digits, e.g.

knitr::kable(dat, format = "markdown", digits = c(1, 32))


| log2fc|   pvalue|
|------:|--------:|
|    0.3| 0.00e+00|
|   10.8| 2.29e-30|
|    8.5| 7.02e-30|
|    5.6| 4.14e-29|
|    8.8| 1.86e-28|
|    6.5| 1.78e-27|
like image 184
user2554330 Avatar answered Nov 07 '22 19:11

user2554330