【问题标题】:Display a data.frame with mathematical notation in table header R Markdown html output在表头 R Markdown html 输出中显示带有数学符号的 data.frame
【发布时间】:2018-05-01 11:53:52
【问题描述】:

假设我想在 R Markdown 文件(html 输出)中显示来自多个方程的系数表。

我希望表格看起来像这样:

但我终生无法弄清楚如何告诉 R Markdown 解析表中的列名。

我得到的最接近的是使用 cat 从我的 data.frame 打印自定义表的 hacky 解决方案......不理想。有没有更好的方法来做到这一点?

这是我如何创建上面的图像,将我的文件保存为 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 = "")
}
```

【问题讨论】:

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


    【解决方案1】:

    您可以使用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)
    ```
    

    【讨论】:

    • 美丽。非常感谢 - 不知道为什么我的搜索中没有出现这个相关问题!
    猜你喜欢
    • 2021-02-07
    • 2018-01-03
    • 2021-10-11
    • 2021-08-06
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    相关资源
    最近更新 更多