sastrup
sastrup

Reputation: 189

RMarkdown Formattable Styling From kableExtra renders html code - not formatted value

When using kableExtra's cell_spec function, I cannot get the rmd document to format the target cell correctly. I can see the html format being applied, but it is rendering the html code itself, not the formatted value. I'm trying to format the p-value of a simple summary stats output.

What ends up rendered in the .html file is below: rendered-table

I'm doing the same thing as below but with my own real data. For reference, this chunk produces the same problem.

mtcars %>% 
  rownames_to_column('car') %>% 
  select(car, mpg, disp, hp, wt) %>% 
  mutate(wt = ifelse(wt < 2, 
                     kableExtra::cell_spec(wt, color = 'red', bold = TRUE), 
                     wt)) %>% 
  kableExtra::kable() %>% 
  kableExtra::kable_styling()

Upvotes: 2

Views: 820

Answers (2)

user2554330
user2554330

Reputation: 44788

The code in the accepted answer no longer works in recent kableExtra versions, because kableExtra::kable is now identical to knitr::kable. To get it to work in the current kableExtra version 1.4.0, use kableExtra::kbl instead:

library(kableExtra)
library(dplyr)

mtcars %>% 
  rownames_to_column('car') %>% 
  select(car, mpg, disp, hp, wt) %>% 
  mutate(wt = ifelse(wt < 2, 
                     kableExtra::cell_spec(wt, color = 'red', bold = TRUE), 
                     wt)) %>% 
  kableExtra::kbl(escape = F) %>% 
  kableExtra::kable_styling()

Upvotes: 2

Paul
Paul

Reputation: 2959

kableExtra::kable(escape = F) is what you want:

library(kableExtra)
library(dplyr)

mtcars %>% 
  rownames_to_column('car') %>% 
  select(car, mpg, disp, hp, wt) %>% 
  mutate(wt = ifelse(wt < 2, 
                     kableExtra::cell_spec(wt, color = 'red', bold = TRUE), 
                     wt)) %>% 
  kableExtra::kable(escape = F) %>% 
  kableExtra::kable_styling()

Upvotes: 2

Related Questions