在 kableExtra 的第 2 列中使用 add_indent() 进行行缩进

Row indentation with add_indent() in 2nd column in kableExtra

我尝试使用 RMarkdown 的 kableExtra 包缩进数据框第二列的单元格。似乎 add_indent() 只适用于第一列,因此在我的 table 下面的 reprex 中没有任何改变:

用虚拟数据表示:

---
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

library(tidyverse)
library(kableExtra)


group <- c(1, NA, NA, 2, NA, NA)
quest <- c("How is your mood today?", "good or very good", "bad or very bad", 
           "What colour is your hair?", "brown", "other")
percent <- c(NA, 80, 20, NA, 50, 50)


df <- tibble(group, quest, percent)


```

## Reprex

```{r, echo=TRUE}
# output without add_indent()
kable(df, booktabs = T, escape = T) %>% 
  add_header_above(header = c("Group" = 1, 
                              "Question & answer options" = 1, 
                              " %Agreement" = 1)) %>% 
  gsub("NA", " ", .)
```


```{r with indent, echo=TRUE}
# output with add_indent()
kable(df, booktabs = T, escape = T) %>% 
  add_header_above(header = c("Group" = 1, 
                              "Question & answer options" = 1, 
                              " %Agreement" = 1)) %>% 
  gsub("NA", " ", .) %>% 
  add_indent(positions = c(2,3,5,6))

期望的输出:我想缩进第 2 列的第 2、3、5、6 行(答案选项位于问题下方,理想情况下也是 斜体).斜体也可以用 cell_spec() 覆盖,但我认为这只适用于列。

我想要的输出可能吗? (我想混合问题和答案选项没有意义,但为了保持早期报告的格式,我们想尝试那样吗?)

这里有两种可能的方法。

  1. 使用 kableExtra::group_rows 代替额外的 group 列。

  2. 使用cell_spec.

    手动添加缩进(kableExtra添加1em

选项 1

```{r, echo = F}
df <- data.frame(quest, percent) 
df %>%
  mutate(quest = cell_spec(quest, italic = ifelse(row_number() %in% c(2,3,5,6), T, F))) %>%
  kable(booktabs = T, escape = F) %>%
  add_indent(c(2,3,5,6)) %>% 
  group_rows("Group 1", 1, 3) %>%
  group_rows("Group 2", 4, 6) %>%
  gsub("NA", " ", .)
```

选项 2

```{r, echo = F}
df <- data.frame(group, quest, percent)
df %>%
  mutate(quest = cell_spec(quest, italic = ifelse(row_number() %in% c(2,3,5,6), T, F)),
         quest = ifelse(row_number() %in% c(2,3,5,6), paste0("\hspace{1em}", quest), quest)) %>%
  kable(booktabs = T, escape = F) %>%
  gsub("NA", " ", .)
```