【问题标题】:Set col names and headers (above) to weird characters for tables with knitr, kableExtra and Latex in R markdown在 R markdown 中为带有 knitr、kableExtra 和 Latex 的表格设置 col 名称和标题(上图)为奇怪的字符
【发布时间】:2018-11-08 03:34:26
【问题描述】:

我正在尝试根据 diamonds 数据集在 Rmarkdown(用于 pdf)中创建一个表,并且我想更改列名上方的一些列名和标题,我想知道如何在其中设置一些标题斜体或粗体,一些标题应该是一个符号(如部分 eta 平方的符号)或一个完整的公式。我已经将我的 R 代码(并且我已经安装了 Latex)与表格一起作为图片(尚未调整)。

```{r setup, include=FALSE}

setwd("~/Desktop/Tables") 
knitr::opts_chunk$set(echo = FALSE)
# global options
options(knitr.table.format = "latex") 
# show space instead of NA in tables
options(knitr.kable.NA = '')
library(tidyverse)
library(knitr)
library(kableExtra)
df = diamonds

```

```{r message=FALSE, warning=FALSE}

df_table = df %>% 
  summarise(avg = round(mean(price), 2),
            sd = round(sd(price), 2),
            n = n(),
            range = round(max(price), 2)) %>% 
  mutate(grouping = "Total") %>% 
  select(grouping, avg, sd, n, range) %>% 
  bind_rows(df %>% 
              group_by(cut) %>% 
              summarise(avg = round(mean(price), 2),
              sd = round(sd(price), 2),
              n = n(),
              range = round(max(price), 2)) %>% 
              mutate(grouping = as.character(cut)) %>% 
              select(grouping, avg, sd, n, range))

kable(df_table,
      booktabs = TRUE,
      linesep = "",
      col.names = c("Grouping", "M in italic", "SD in italic", "N not 
italic", "some weird formula for the range" )) %>%
  kable_styling(latex_options = c("HOLD_position", "scale_down")) %>% 
  add_header_above(c(" " = 1, "the formula for the variance" = 4))

```

【问题讨论】:

    标签: r r-markdown knitr tabular kableextra


    【解决方案1】:

    在您的调用中将escape = FALSE 设置为kableadd_header_above,并在您的列标题中使用LaTeX。我应该承认,究竟应该添加多少反斜杠才能获得所需的结果,这对我来说是个谜。

    kable(df_table,
          booktabs = TRUE,
          linesep = "",
          col.names = c("Grouping", "$M$", "$SD$", "N", "$\\eta$"), escape = FALSE) %>%
      kable_styling(latex_options = c("HOLD_position", "scale_down")) %>% 
      add_header_above(c(" " = 1, "$\\\\operatorname{Var}[X]$" = 4), escape = FALSE)
    

    【讨论】:

    • 尤伯盖尔!非常感谢,我认为在我的其他关于表格的帖子中,应该能够构建最漂亮的表格,很好,因为我在 kableExtra 表格的官方文档中找不到所有这些
    • 谢谢!不幸的是,百分比似乎不适用于这种方法。我尝试了 \ 和 $ 的各种组合。有关如何使其工作的任何建议?
    • 更新,我可以用 \\% 显示百分号,但它破坏了我的表格,因为它有括号。 ://
    猜你喜欢
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多