在表头R Markdown html输出中使用数学符号显示data.frame

时间:2017-11-17 16:27:08

标签: r html-table r-markdown mathematical-expressions

我想在R Markdown文件(html输出)中显示几个方程式的系数表。

我希望桌子看起来像这样:

enter image description here

但我不能为我的生活弄清楚如何告诉R Markdown解析表中的列名。

我最接近的是一个hacky解决方案,使用cat从我的data.frame打印自定义表...不理想。有更好的方法吗?

这是我如何创建上面的图片,将我的文件保存为RStudio中的.Rmd。

---
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 = "")
}
```

1 个答案:

答案 0 :(得分:5)

您可以使用kable()及其escape选项格式化数学符号(请参阅this answer相关问题)。然后你将你的肮脏标题指定为列名,然后你去:

---
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