Ahdee
Ahdee

Reputation: 4949

R markdown kable strikethrough row(s)?

Hi I have table that I would like to print in using kable.

ds <- read.table(header = TRUE, text ="
                 g1 color
                 A red
                 A yellow
                 B red
                 C red
                 C yellow
                 ")

so let say in when this prints to pdf is it possible to have the entire row strikethough if it contains "yellow"?

thanks in advance. A.

Upvotes: 1

Views: 558

Answers (2)

Jai
Jai

Reputation: 321

Hat tip to Hao Zhu

library(kableExtra)
library(formattable)
library(dplyr)

ds <- read.table(header = TRUE, text ="
                 g1 color
                 A red
                 A yellow
                 B red
                 C red
                 C yellow
                 ")

ds %>% as.data.frame() %>% mutate_if(is.factor,as.character) %>%
mutate(
g1 = ifelse(
  color == "yellow", 
  paste0("\\sout{", g1, "}"), g1
  ), color = ifelse(
  color == "yellow", 
  paste0("\\sout{", color, "}"), color
  )
) %>%
kable("latex", escape = F, booktabs = T)

Note: need to include ulem TeX package while compiling (e.g., YAML header of Rmd document)

Upvotes: 1

Jai
Jai

Reputation: 321

Use package: 'formattable' to do this in html. Not sure about pdf.

library(formattable)
ds <- read.table(header = TRUE, text ="
             g1 color
             A red
             A yellow
             B red
             C red
             C yellow
             ")

formattable(ds, list(
area(row = which(ds$color == "yellow")) ~ formatter("span",
  style = "text-decoration:line-through")))

If you want to use kable then you can mutate the row with formatter function and use kableExtras package to output to html

library(kableExtra)
library(formattable)
library(dplyr)

    ds <- read.table(header = TRUE, text ="
                     g1 color
                     A red
                     A yellow
                     B red
                     C red
                     C yellow
                     ")

    ds <- ds %>% mutate(g1 = formatter("span",
        style = x ~ style("text-decoration" = ifelse(ds$color == "yellow", "line-through", NA)))(g1),
        color = formatter("span",
        style = x ~ style("text-decoration" = ifelse(ds$color == "yellow", "line-through", NA)))(color))

    kable(ds, "html", escape = F)

At this point you can knit to html and use a html to pdf converter and call a system command from R.

system("wkhtmltopdf --javascript-delay 1 --dpi 300 in.html out.pdf")

Upvotes: 1

Related Questions