2

我正在尝试根据 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))

```

在此处输入图像描述

4

1 回答 1

7

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)

在此处输入图像描述

于 2018-05-29T13:17:28.903 回答