Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use knitr to apply CSS styles to individual table cells?

Tags:

html

css

r

knitr

Is it possible to apply a class attribute to individual table cells using knitr? I have successfully applied a class attribute to the section heading that contains a knitr::kable generated table and used that to format the entire table. However, I would like to be able to conditionally format individual cells which would require being able to apply a class to specific <td> elements.

My current workaround is to programmatically wrap the cell contents in a pair of <span> tags and pass that on to knitr::kable. This approach only allows me to format the text inside the cell versus the entire cell (e.g. setting the cell background color). Here's an example of what I'm currently using:

## Read in the report, process the data, send to kable
rpt <- generate.report()
mutate(rpt, Col2 = ifelse(abs(Col2) > Threshold,
                          paste('<span class="warning">',
                                sprintf("%.2f", Col2), '</span>'),
                          sprintf("%.2f", Col2))) %>%
  knitr::kable(format="markdown", align = c("l", rep("r", 4)),
               col.names = gsub("\\.", "<br>", colnames(.)))

Which results in the following example HTML output:

<td align="right"><span class="warning"> -1.74 </span></td>

I would like to be able to have knitr::kable generate something like this:

<td align="right" class="warning"> -1.74 </td>

That way I could apply css styles to the <td> tag vice the <span> tag.

like image 227
Daddy the Runner Avatar asked Dec 30 '14 04:12

Daddy the Runner


1 Answers

package ReporteRs may help. Have a look here FlexTable.

You can then get the corresponding HTML code with function as.html and reuse it within your knitr code.

like image 72
David Gohel Avatar answered Nov 11 '22 00:11

David Gohel