Nick Knauer
Nick Knauer

Reputation: 4243

Bold a column in knitr::kable(df)

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!

Upvotes: 2

Views: 2391

Answers (1)

user2554330
user2554330

Reputation: 44997

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.

Upvotes: 2

Related Questions