Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a data.frame with mathematical notation in table header R Markdown html output

Say I'd like to display a table of coefficients from several equations in an R Markdown file (html output).

I'd like the table to look somewhat like this:

enter image description here

But I can't for the life of me figure out how to tell R Markdown to parse the column names in the table.

The closest I've gotten is a hacky solution using cat to print custom table from my data.frame... not ideal. Is there a better way to do this?

Here's how I created the image above, saving my file as an .Rmd in RStudio.

---
title: "Math in R Markdown tables"
output:
  html_notebook: default
  html_document: default
---

My fancy table

```{r, echo=FALSE, include=TRUE, results="asis"}
# Make data.frame
mathy.df <- data.frame(site = c("A", "B"), 
                       b0 = c(3, 4), 
                       BA = c(1, 2))

# Do terrible things to print it properly
cat("Site|$\\beta_0$|$\\beta_A$")
cat("\n")
cat("----|---------|---------\n")

for (i in 1:nrow(mathy.df)){
  cat(as.character(mathy.df[i,"site"]), "|", 
      mathy.df[i,"b0"], "|", 
      mathy.df[i,"BA"], 
      "\n", sep = "")
}
```
like image 255
Nova Avatar asked Mar 08 '23 13:03

Nova


1 Answers

You can use kable() and its escape option to format math notation (see this answer to a related question). Then you assign your mathy headings as the column names, and there you go:

---
title: "Math in R Markdown tables"
output:
  html_notebook: default
  html_document: default
---

My fancy table

```{r, echo=FALSE, include=TRUE, results="asis"}
library(knitr)

mathy.df <- data.frame(site = c("A", "B"), 
                       b0 = c(3, 4), 
                       BA = c(1, 2))

colnames(mathy.df) <- c("Site", "$\\beta_0$", "$\\beta_A$")

kable(mathy.df, escape=FALSE)
```

enter image description here

like image 184
duckmayr Avatar answered Mar 10 '23 14:03

duckmayr