Home > Mobile >  kableExtra formatting table formatting scientific exponents
kableExtra formatting table formatting scientific exponents

Time:10-13

I am trying to format a table. I noticed that one column doesn't have the formatting that I want. In the picture below, you can see that the values in the column titled "p-value" are presented like "1.0x10^-5". I can't seem to figure out why the x in that column is italicized. What I really want the column to look like is each value to be present like this "1.0 x 10^-5" with no italicized x and spaces before and after the "x". I was wondering if anyone had any idea on how to fix this? I added an example dataset below as well as the code I used to create the table.

enter image description here Example code :

 kbl(df.test, format = "html", table.attr = "style='width:40%;'", escape = F, align = "r") %>%
      kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive")) %>%
      kable_classic(full_width = F, html_font = "Times New Roman")

Example data:

structure(list(SNP = c("abc", "abc", "abc"), Gene = c("xyz", 
"xyz", "xyz"), Cases = c(87L, 86L, 72L), `% Population` = structure(19:17, .Label = c("$12.4^{ 5.3}_{-4.2}$", 
"$12.7^{ 5.4}_{-4.3}$", "$13.3^{ 5.4}_{-4.4}$", "$13.6^{ 5.5}_{-4.4}$", 
"$13.9^{ 5.5}_{-4.4}$", "$13.9^{ 5.5}_{-4.5}$", "$14.2^{ 5.5}_{-4.5}$", 
"$14.8^{ 5.6}_{-4.6}$", "$15.4^{ 5.7}_{-4.7}$", "$16.0^{ 5.8}_{-4.8}$", 
"$16.3^{ 5.8}_{-4.8}$", "$17.2^{ 5.9}_{-4.9}$", "$19.8^{ 6.2}_{-5.3}$", 
"$20.4^{ 6.2}_{-5.3}$", "$20.7^{6.2}_{-5.4}$", "$21.0^{ 6.2}_{-5.4}$", 
"$21.3^{ 6.3}_{-5.4}$", "$25.4^{ 6.6}_{-5.9}$", "$25.7^{ 6.6}_{-5.9}$"
), class = "factor"), p.value = structure(c(12L, 14L, 18L), .Label = c("$1.0 x 10^{-5}$", 
"$1.1 x 10^{-4}$", "$1.2 x 10^{-5}$", "$1.3 x 10^{-3}$", "$1.4 x 10^{-5}$", 
"$1.5 x 10^{-3}$", "$1.7 x 10^{-4}$", "$2.0 x 10^{-4}$", "$2.0 x 10^{-5}$", 
"$2.9 x 10^{-4}$", "$4.0 x 10^{-4}$", "$5.2 x 10^{-7}$", "$5.6 x 10^{-4}$", 
"$6.3 x 10^{-7}$", "$6.6  x 10^{-4}$", "$6.6 x 10^{-4}$", "$7.8 x 10^{-4}$", 
"$8.5 x 10^{-6}$", "$9.2 x 10^{-4}$"), class = "factor")), row.names = c(NA, 
3L), class = "data.frame")

CodePudding user response:

If we leave out the x from the dollar signs, it won't be formatted as an equation, e.g.

library(dplyr)
library(kableExtra))

data %>% mutate(p.value = gsub(x = p.value, pattern = " x ", replacement = "$ x $")) %>% # Replace "x" with "$ x $"
  kbl(format = "html", table.attr = "style='width:40%;'", escape = F, align = "r") %>%
  kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive")) %>%
  kable_classic(full_width = F, html_font = "Times New Roman")

enter image description here

  • Related