2

I have a dataframe that looks as follows:

---
title: "Untitled"
output: html_document
---
```{r}
employee <- c('John Doe','Peter Gynn','Jolie Hope')
salary <- c(21000, 23400, 26800)
startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14'))

employ.data <- data.frame(employee, salary, startdate)

knitr::kable(employ.data)
```

Does anyone know how to bold the salary column?

It's going to be in an html format in the end.

enter image description here

Thanks!

nak5120
  • 4,089
  • 4
  • 35
  • 94
  • May be this http://stackoverflow.com/questions/28166168/how-to-bold-a-cell-in-a-table-kable-in-rmarkdown helps – akrun Nov 22 '16 at 16:39
  • Would that work in an html format? I changed up the question to make it clearer @akrun – nak5120 Nov 22 '16 at 16:44
  • For flexible formatting of tables for `html` output, you might look at the [`htmlTable` package](https://cran.r-project.org/web/packages/htmlTable/vignettes/general.html) or the [`FlexTable` function](http://davidgohel.github.io/ReporteRs/articles/FlexTable.html) in the [`ReporteRs` package](http://davidgohel.github.io/ReporteRs/). – eipi10 Nov 22 '16 at 16:52
  • Also check out [`formattable`](https://renkun.me/formattable/) – Jake Kaupp Nov 22 '16 at 17:37

1 Answers1

2

You can use CSS to do it, as described here: Using CSS how to change only the 2nd column of a table.

You can just put the CSS directly into the text, outside of the code chunk, or in a separate file mentioned in the YAML header. For example,

<style>
table td:nth-child(2){
    font-weight: bold;
}
</style>

```{r}
employee <- c('John Doe','Peter Gynn','Jolie Hope')
salary <- c(21000, 23400, 26800)
startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14'))

employ.data <- data.frame(employee, salary, startdate)

knitr::kable(employ.data)
```

This will change every table in the document; you may want a more specific selector.

I don't know a simple way to add a class to a particular table using kable() in R Markdown, but this kludge will do it. In the CSS, use

<style>
table.salarytable td:nth-child(2){
    font-weight: bold;
}
</style>

to restrict the change to class salarytable, then in the code chunk use

knitr::kable(employ.data, "html", 
             table.attr = 'class="table table-condensed salarytable"'

to tell knitr to output HTML and give the table the usual class for an R Markdown table, as well as your own salarytable class.

Community
  • 1
  • 1
user2554330
  • 37,248
  • 4
  • 43
  • 90
  • Thank you! I think the 2nd option you gave would work best for my needs since there are going to be multiple tables with different formats. @user2554330 – nak5120 Nov 23 '16 at 14:14