1

Let's consider this simple data frame produced by kable function:

library(knitr)

df <- data.frame("X_1" = c(0.9131357, 0.9022396), "X_2" = c(6.328998e-07, 1.607509e-07))
kable(df, format = "pipe", digits = 3)

|   X_1| X_2|
|-----:|---:|
| 0.913|   0|
| 0.902|   0|

My question is - is there any possibility to add trailing zeroes to X_2 ? i.e. to have 0.000 instead of just 0 - it looks much better in my opinion when decimal places are equal for each column.

John
  • 1,849
  • 2
  • 13
  • 23

2 Answers2

0

it's not very elegant, but this works for me:

df2 <- data.frame(X_1=df$X_1, X_2=sprintf("%.03f", df$X_2))
kable(df2, format = "pipe", digits = 3, align="r")
|   X_1|   X_2|
|-----:|-----:|
| 0.913| 0.000|
| 0.902| 0.000|
brian avery
  • 403
  • 2
  • 8
0

You can use format.args (see kable documentation as well as ?format), specifically the nsmall option:

> library(knitr)
> df <- data.frame("X_1" = c(0.9131357, 0.9022396), "X_2" = c(6.328998e-07, 1.607509e-07))
> kable(df, format = "pipe", digits = 3, format.args = list(nsmall = 3))

|   X_1|   X_2|
|-----:|-----:|
| 0.913| 0.000|
| 0.902| 0.000

digits = 3 ensures that at most 3 decimal places are used, and nsmall = 3 ensures at at least 3 decimal places are used. With both of these together you get the desired result.

orthocresol
  • 657
  • 8
  • 9