0

I have to create a table manually as follows in Rmarkdown.

library(knitr)
library(kableExtra)

x <- cbind(c("Term", "Intercept"),
           c( "Estimate", round(2.684698447, digits = 3)), 
           c("P-value", "$< 2 \\times 10^{-16}$"),
           c("Significance", "***"))

 
knitr::kable(x, align="c", escape = F, caption = "Summary of the fitted linear model with miles per gallon as the response variable. Significance codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1",
      booktabs = T) %>%
  kable_styling("hover", full_width = F, font_size = 11, latex_options = "hold_position"
                )%>%
  row_spec(0, bold = T, font_size = 12) %>%
  column_spec(1, border_right = TRUE)  %>%
  row_spec(3, hline_after = TRUE)

and the table looks like this:

enter image description here

However, I want a line to be below the header. How should I do that?

Abbas
  • 807
  • 7
  • 14

1 Answers1

2

You would have that line by the default booktab style if you had set the row Term Estimate P-value Significance as the data frame header and pass that data to kable()

---
title: "Table Header"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

```{r}
library(knitr)
library(kableExtra)

x <- cbind(c("Term", "Intercept"),
           c( "Estimate", round(2.684698447, digits = 3)), 
           c("P-value", "$< 2 \\times 10^{-16}$"),
           c("Significance", "***"))

x <- as.data.frame(x) # set as dataframe

x <- janitor::row_to_names(x, 1, remove_rows_above = FALSE) # set the 1st row as header

rownames(x) <- NULL
 
knitr::kable(x, align="c", escape = F, caption = "Summary of the fitted linear model with miles per gallon as the response variable. Significance codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1",
      booktabs = T) %>%
  kable_styling("hover", full_width = F, font_size = 11, latex_options = "hold_position"
                )%>%
  row_spec(0, bold = T, font_size = 12) %>%
  column_spec(1, border_right = TRUE)
```


kable with booktab style

Note that, you would need to install the package {janitor} to get the above code work.

shafee
  • 15,566
  • 3
  • 19
  • 47